<?php

declare(strict_types=1);

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/04/21
//      |_|                                         | TpMeCMS

namespace ImiApp\ApiServer\Api\Controller;


use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;


use ImiApp\ApiServer\Api\Controller\CommonController;
use Imi\Db\Db;
use Imi\Config;


use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

use ImiApp\ApiServer\Api\Model\Goodscate;


/**
 * 
 * @Auth(name="token",nologin={"*"})
 * @Controller("/tpmecmscom/")
 */
class Tpmecmscom extends ApiBase
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    // 获取数据缓存时间秒
    protected $db_cache_set = 10;

    // public function _initialize()
    // {
    //     parent::_initialize();
    //     $this->db_cache_set = config('db_cache_set');
    // }

    /**
     * 可在继承app\common\controller\Tpmecms 下面的里面直接使用该控制器里面的方法 使用方法：$this->p_tpmecsm();
     *
     * @return void
     */
    protected function p_tpmecms()
    {

        return $this->success('TpMeCms', ['com' => 'TpMeCMS']);
    }

    public function 用户上月提成($user_id, $date = null)
    {
        if (!$date)
            $date = date('Y-m');
        list($上月开始, $上月结束) = $this->GetMonthTime(date('Y-m', strtotime('last month', strtotime($date))));
        $where_com['user_id'] = $user_id;
        $上月提成 = Db::name('user_commission_log')
            ->whereEx($where_com)
            ->where('createtime', '>=', $上月开始)
            ->where('createtime', '<', $上月结束)
            ->sum('commission');
        return $上月提成 ?? 0;
    }

    public function 用户某月提成($user_id, $date = null)
    {
        if (!$date)
            $date = date('Y-m');
        list($月开始, $月结束) = $this->GetMonthTime($date);
        $where_com['user_id'] = $user_id;
        $月提成 = Db::name('user_commission_log')
            ->whereEx($where_com)
            ->where('createtime', '>=', $月开始)
            ->where('createtime', '<', $月结束)
            ->sum('commission');
        return $月提成 ?? 0;
    }




    public function 获取子订单店铺收款金额($order_item)
    {
        $data['store_pay_fee'] = 0;
        $data['store_money_service_fee'] = 0;

        $data['store_score_fee'] = 0;
        $data['store_score_service_fee'] = 0;

        $data['store_shell_fee'] = 0;
        $data['store_shell_service_fee'] = 0;

        $data['coupons_sys_give_shell'] = 0;


        $store_id = $order_item['store_id'];
        $_支付的现金_ = $order_item['pay_fee'];

        $goods = Db::name('goods')->where('id', '=', $order_item['goods_id'])->find();
        $goodscate2 = Db::name('goodscate')->where('id', '=', $goods['goodscate_ids'])->find();

        $商品分类系数 = 0;
        if ($goodscate2['goodscate_ratio'] > 0) {
            $商品分类系数 = $goodscate2['goodscate_ratio'];
        } else {
            $goodscate1 = Db::name('goodscate')->where('id', '=', $goodscate2['pid'])->find();
            if ($goodscate1['goodscate_ratio'] > 0) {
                $商品分类系数 = $goodscate1['goodscate_ratio'];
            }
        }

        var_dump('商品分类系数转换前:', $商品分类系数);
        $商品分类系数 = $this->ChangeRatio($商品分类系数);
        var_dump('商品分类系数转换后:', $商品分类系数);


        $goodsbrand = Db::name('goodsbrand')->where('id', '=', $goods['goodsbrand_id'])->find();
        if ($goodsbrand && $goodsbrand['goodsbrand_ratio'] > 0) {
            $品牌系数 = $goodsbrand['goodsbrand_ratio'];
        } else {
            $品牌系数 = 1;
        }


        $_卖家给平台的现金服务费_ = 0;
        if ($order_item['pay_fee'] > 0) {

            // 商品类型:=实体商品,virtual=虚拟商品,service=服务
            switch ($order_item['goods_type']) {
                case 'normal':
                    //实体商品
                    $现金服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 8); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%

                    $现金服务费比例 = $this->ChangeRatio($现金服务费比例);
                    var_dump('邮寄现金服务费比例' . $现金服务费比例);
                    break;

                default:
                    $现金服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 9); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%

                    $现金服务费比例 = $this->ChangeRatio($现金服务费比例);
                    var_dump('服务现金服务费比例' . $现金服务费比例);
                    break;
            }



            if ($goods['goods_service_ratio'] > 0) {
                $_卖家给平台的现金服务费_ = $_支付的现金_ * $现金服务费比例 * $this->ChangeRatio($goods['goods_service_ratio']);
                var_dump('商品服务比例goods_service_ratio', $goods['goods_service_ratio'], $this->ChangeRatio($goods['goods_service_ratio']));
            } else {
                
                // $_卖家给平台的现金服务费_ = $_支付的现金_ * $现金服务费比例 * $商品分类系数 * $this->ChangeRatio($品牌系数);//2023-08-15注释 
            }


            $最终收得现金 =  $_支付的现金_ -  $_卖家给平台的现金服务费_;

            \Imi\Log\Log::info('买家确认收货,扣除店铺现金服务费' . $_卖家给平台的现金服务费_ . '= 现金' . $_支付的现金_ . '* 现金服务费比例' . $现金服务费比例 . '* (商品分类系数' . $商品分类系数 . '* 品牌系数)' . $this->ChangeRatio($品牌系数));
            if ($最终收得现金 < $this->ChangeRatio((float)config('money_service_ratio') / 100)) {
                \Imi\Log\Log::error('买家确认收货,扣除店铺现金服务费是否正确?' . $_卖家给平台的现金服务费_ . '= 现金' . $_支付的现金_ . '* 现金服务费比例' . $现金服务费比例 . '* 商品分类系数' . $商品分类系数 . '* 品牌系数' . $this->ChangeRatio($品牌系数));
            }

            // `store_pay_fee` decimal(10,2) DEFAULT '0.00' COMMENT '店铺收款金额',
            // `store_score_fee` decimal(11,2) DEFAULT '0.00' COMMENT '店铺收积分',
            // `store_shell_fee` decimal(10,2) DEFAULT '0.00' COMMENT '店铺收贝壳总数',
            // `store_money_service_fee` decimal(10,2) DEFAULT NULL COMMENT '店铺现金服务费',
            // `store_score_service_fee` decimal(11,2) DEFAULT '0.00' COMMENT '店铺积分服务费',
            // `store_shell_service_fee` decimal(10,2) DEFAULT '0.00' COMMENT '店铺贝壳服务费',

            $data['store_pay_fee'] = $最终收得现金;
            $data['store_money_service_fee'] = $_卖家给平台的现金服务费_;

            // $data['store_score_fee'] = $最终收得现金;
            // $data['store_score_service_fee'] = $最终收得现金;

            // $data['store_shell_fee'] = $最终收得现金;
            // $data['store_shell_service_fee'] = $最终收得现金;

        }


        

        //把订单里面的积分给商家 
        if ($order_item['score_fee'] > 0) {
            $积分服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 6); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
            $积分服务费比例 = $this->ChangeRatio($积分服务费比例);
            $支付的积分 = $order_item['score_fee'];
            $给平台的积分服务费 = $积分服务费比例 * $支付的积分;
            $最终收得积分 =  $支付的积分 -  $给平台的积分服务费;


            if ($最终收得积分 > 0) {
                $data['store_score_fee'] = $最终收得积分;
                $data['store_score_service_fee'] = $给平台的积分服务费;
            }
        }



        //把订单里面的贝壳给商家
        if ($order_item['shell_fee'] > 0) {

            $贝壳服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 5); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=贝壳服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
            $贝壳服务费比例 = $this->ChangeRatio($贝壳服务费比例);
            $支付的贝壳 = $order_item['shell_fee'];
            $给平台的贝壳服务费 = $贝壳服务费比例 * $支付的贝壳;
            $最终收得贝壳 =  $支付的贝壳 -  $给平台的贝壳服务费;

            \Imi\Log\Log::info('买家确认收货,_卖家最终收得贝壳' . $最终收得贝壳 . '= 支付的贝壳' . $支付的贝壳 . '- 给平台的贝壳服务费' . $给平台的贝壳服务费);
            if ($最终收得贝壳) {

                $data['store_shell_fee'] = $最终收得贝壳;
                $data['store_shell_service_fee'] = $给平台的贝壳服务费;
            }
        }

        if ($order_item['coupon_fee'] > 0) {
            $贝壳服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 5); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=贝壳服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
            $贝壳服务费比例 = $this->ChangeRatio($贝壳服务费比例);

            //如果有使用平台优惠券也要给商家加贝壳
            $使用平台优惠券抵扣的金额 = $order_item['coupon_fee'];
            $平台给返店铺的贝壳 = $使用平台优惠券抵扣的金额 - $贝壳服务费比例 * $使用平台优惠券抵扣的金额;
            if ($平台给返店铺的贝壳 > 0) {
                $data['coupons_sys_give_shell'] = $平台给返店铺的贝壳;
            }
            var_dump('使用平台优惠券' . $使用平台优惠券抵扣的金额 . ' 返贝壳' . $data['coupons_sys_give_shell'] . '贝壳服务费比例' . $贝壳服务费比例);
        }

        return $data;
    }



    public function 获取拍卖出局总补贴贝壳($auction,$first){
        $auction_id = $$auction['id'];
        //enroll_status	enroll_status	8		状态:1=未报名,2=已报名
     
        $未报名数 = Db::name('auction_offer')->where('auction_id','=',$auction_id)->where('enroll_status','=','1')->count();
        $报名数 = Db::name('auction_offer')->where('auction_id','=',$auction_id)->where('enroll_status','=','2')->count();

        if($first){
            if($first['enroll_status']=='1'){
                $未报名数 = $未报名数 - 1;
            }else{
                $报名数 = $报名数 - 1;
            }
        }
        return $未报名数 * $auction['enroll_out_perk_shell'] + $报名数 * $auction['out_perk_shell'];
    }




    public function 获取拍卖子订单店铺收款金额($order_item)
    {
        $data['store_pay_fee'] = 0;
        $data['store_money_service_fee'] = 0;

        $data['store_score_fee'] = 0;
        $data['store_score_service_fee'] = 0;

        $data['store_shell_fee'] = 0;
        $data['store_shell_service_fee'] = 0;

        $data['coupons_sys_give_shell'] = 0;


        $store_id = $order_item['store_id'];
        $_支付的现金_ = $order_item['pay_fee'];

        $goods = Db::name('goods')->where('id', '=', $order_item['goods_id'])->find();
        $goodscate2 = Db::name('goodscate')->where('id', '=', $goods['goodscate_ids'])->find();

        $商品分类系数 = 0;
        if ($goodscate2['goodscate_ratio'] > 0) {
            $商品分类系数 = $goodscate2['goodscate_ratio'];
        } else {
            $goodscate1 = Db::name('goodscate')->where('id', '=', $goodscate2['pid'])->find();
            if ($goodscate1['goodscate_ratio'] > 0) {
                $商品分类系数 = $goodscate1['goodscate_ratio'];
            }
        }

        var_dump('商品分类系数转换前:', $商品分类系数);
        $商品分类系数 = $this->ChangeRatio($商品分类系数);
        var_dump('商品分类系数转换后:', $商品分类系数);


        $goodsbrand = Db::name('goodsbrand')->where('id', '=', $goods['goodsbrand_id'])->find();
        if ($goodsbrand && $goodsbrand['goodsbrand_ratio'] > 0) {
            $品牌系数 = $goodsbrand['goodsbrand_ratio'];
        } else {
            $品牌系数 = 1;
        }


        $_卖家给平台的现金服务费_ = 0;
        if ($order_item['pay_fee'] > 0) {

            // 商品类型:=实体商品,virtual=虚拟商品,service=服务
            switch ($order_item['goods_type']) {
                case 'normal':
                    //实体商品
                    $现金服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 8); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%

                    $现金服务费比例 = $this->ChangeRatio($现金服务费比例);
                    var_dump('邮寄现金服务费比例' . $现金服务费比例);
                    break;

                default:
                    $现金服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 9); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%

                    $现金服务费比例 = $this->ChangeRatio($现金服务费比例);
                    var_dump('服务现金服务费比例' . $现金服务费比例);
                    break;
            }



            if ($goods['goods_service_ratio'] > 0) {
                $_卖家给平台的现金服务费_ = $_支付的现金_ * $现金服务费比例 * $this->ChangeRatio($goods['goods_service_ratio']);
                var_dump('商品服务比例goods_service_ratio', $goods['goods_service_ratio'], $this->ChangeRatio($goods['goods_service_ratio']));
            } else {
                
                // $_卖家给平台的现金服务费_ = $_支付的现金_ * $现金服务费比例 * $商品分类系数 * $this->ChangeRatio($品牌系数);//2023-08-15注释 
            }


            $最终收得现金 =  $_支付的现金_ -  $_卖家给平台的现金服务费_;

            \Imi\Log\Log::info('买家确认收货,扣除店铺现金服务费' . $_卖家给平台的现金服务费_ . '= 现金' . $_支付的现金_ . '* 现金服务费比例' . $现金服务费比例 . '* (商品分类系数' . $商品分类系数 . '* 品牌系数)' . $this->ChangeRatio($品牌系数));
            if ($最终收得现金 < $this->ChangeRatio((float)config('money_service_ratio') / 100)) {
                \Imi\Log\Log::error('买家确认收货,扣除店铺现金服务费是否正确?' . $_卖家给平台的现金服务费_ . '= 现金' . $_支付的现金_ . '* 现金服务费比例' . $现金服务费比例 . '* 商品分类系数' . $商品分类系数 . '* 品牌系数' . $this->ChangeRatio($品牌系数));
            }

            // `store_pay_fee` decimal(10,2) DEFAULT '0.00' COMMENT '店铺收款金额',
            // `store_score_fee` decimal(11,2) DEFAULT '0.00' COMMENT '店铺收积分',
            // `store_shell_fee` decimal(10,2) DEFAULT '0.00' COMMENT '店铺收贝壳总数',
            // `store_money_service_fee` decimal(10,2) DEFAULT NULL COMMENT '店铺现金服务费',
            // `store_score_service_fee` decimal(11,2) DEFAULT '0.00' COMMENT '店铺积分服务费',
            // `store_shell_service_fee` decimal(10,2) DEFAULT '0.00' COMMENT '店铺贝壳服务费',

            $data['store_pay_fee'] = $最终收得现金;
            $data['store_money_service_fee'] = $_卖家给平台的现金服务费_;

            // $data['store_score_fee'] = $最终收得现金;
            // $data['store_score_service_fee'] = $最终收得现金;

            // $data['store_shell_fee'] = $最终收得现金;
            // $data['store_shell_service_fee'] = $最终收得现金;

        }

        //把订单里面的积分给商家 
        if ($order_item['score_fee'] > 0) {
            $积分服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 6); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
            $积分服务费比例 = $this->ChangeRatio($积分服务费比例);
            $支付的积分 = $order_item['score_fee'];
            $给平台的积分服务费 = $积分服务费比例 * $支付的积分;
            $最终收得积分 =  $支付的积分 -  $给平台的积分服务费;


            if ($最终收得积分 > 0) {
                $data['store_score_fee'] = $最终收得积分;
                $data['store_score_service_fee'] = $给平台的积分服务费;
            }
        }



        //把订单里面的贝壳给商家
        if ($order_item['shell_fee'] > 0) {

            $贝壳服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 5); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=贝壳服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
            $贝壳服务费比例 = $this->ChangeRatio($贝壳服务费比例);
            $支付的贝壳 = $order_item['shell_fee'];
            $给平台的贝壳服务费 = $贝壳服务费比例 * $支付的贝壳;
            $最终收得贝壳 =  $支付的贝壳 -  $给平台的贝壳服务费;

            \Imi\Log\Log::info('买家确认收货,_卖家最终收得贝壳' . $最终收得贝壳 . '= 支付的贝壳' . $支付的贝壳 . '- 给平台的贝壳服务费' . $给平台的贝壳服务费);
            if ($最终收得贝壳) {

                $data['store_shell_fee'] = $最终收得贝壳;
                $data['store_shell_service_fee'] = $给平台的贝壳服务费;
            }
        }

        if ($order_item['coupon_fee'] > 0) {
            $贝壳服务费比例 = $this->GetSetserverstoreVal($store_id, $order_item['store_set_id'], 5); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=贝壳服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
            $贝壳服务费比例 = $this->ChangeRatio($贝壳服务费比例);

            //如果有使用平台优惠券也要给商家加贝壳
            $使用平台优惠券抵扣的金额 = $order_item['coupon_fee'];
            $平台给返店铺的贝壳 = $使用平台优惠券抵扣的金额 - $贝壳服务费比例 * $使用平台优惠券抵扣的金额;
            if ($平台给返店铺的贝壳 > 0) {
                $data['coupons_sys_give_shell'] = $平台给返店铺的贝壳;
            }
            var_dump('使用平台优惠券' . $使用平台优惠券抵扣的金额 . ' 返贝壳' . $data['coupons_sys_give_shell'] . '贝壳服务费比例' . $贝壳服务费比例);
        }

        return $data;
    }


    public function 获取用户的上级和上上级($user_id)
    {

        $data['user_pid_id'] = 0;
        $data['user_pid_set_id'] = 0;
        $data['user_ppid_id'] = 0;
        $data['user_ppid_set_id'] = 0;
        $puser = $this->getUserPidUser($user_id);
        $data['user_set_id'] = $puser['self_set_id'];
        if ($puser && isset($puser['id'])) {
            $data['user_pid_id'] = $puser['id'];
            $data['user_pid_set_id'] = $puser['set_id'];
            if ($puser['pid'] > 0) {
                $ppuser = $this->getUserPidUser($puser['pid']);
                if ($ppuser && isset($ppuser['id'])) {
                    $data['user_ppid_id'] = $ppuser['id'];
                    $data['user_ppid_set_id'] = $ppuser['set_id'];
                }
            }
        }
        return $data;
    }

    public function 获取店铺的上级和上上级($store_id)
    {
        $data['store_pid_id'] = 0;
        $data['store_pid_set_id'] = 0;
        $data['store_ppid_id'] = 0;
        $data['store_ppid_set_id'] = 0;
        $puser = $this->getStorePidUser2($store_id);
        $data['store_set_id'] = $puser['self_set_id'];
        if ($puser && isset($puser['id'])) {
            $data['store_pid_id'] = $puser['id'];
            $data['store_pid_set_id'] = $puser['set_id'];
            if ($puser['pid'] > 0) {
                $ppuser = $this->getStorePidUser2($puser['pid']);
                if ($ppuser && isset($ppuser['id'])) {
                    $data['store_ppid_id'] = $ppuser['id'];
                    $data['store_ppid_set_id'] = $ppuser['set_id'];
                }
            }
        }
        return $data;
    }


    public function 冻结拍卖全部库存($auction, $ps)
    {
        //退回库存
        if ($auction['stock_status'] == 'freeze') {
            $goods_sku_price_arr = explode(',', $auction['goods_sku_price_ids']);
            foreach ($goods_sku_price_arr as $key => $sku_id) {
                $this->DecGoodsStock($sku_id, 1, $ps, $auction['id']);
            }
            Db::name('auction')->where('id', '=', $auction['id'])->update(['stock_status' => 'unfreeze']);
        }
    }


    public function 解冻拍卖全部库存($auction, $ps)
    {
        //退回库存
        if ($auction['stock_status'] == 'freeze') {
            $goods_sku_price_arr = explode(',', $auction['goods_sku_price_ids']);
            foreach ($goods_sku_price_arr as $key => $sku_id) {
                $this->IncGoodsStock($sku_id, 1, $ps, $auction['id']);
            }
            Db::name('auction')->where('id', '=', $auction['id'])->update(['stock_status' => 'unfreeze']);
        }
    }

    public function 解冻拍卖部分库存($auction, $ps, $拍中库存id)
    {
        //退回库存
        if ($auction['stock_status'] == 'freeze') {
            $goods_sku_price_arr = explode(',', $auction['goods_sku_price_ids']);
            foreach ($goods_sku_price_arr as $key => $sku_id) {
                if ($拍中库存id != $sku_id)
                    $this->IncGoodsStock($sku_id, 1, $ps, $auction['id']);
            }
            Db::name('auction')->where('id', '=', $auction['id'])->update(['stock_status' => 'unfreeze_unfreeze_some']);
        }
    }

    /**
     * 
     * @param int $goods_id 商品id
     * @param mixed $goods_sku_price_ids 商品库存规格id
     */
    public function 验证商品是否含有这个库存规格($goods_id, $goods_sku_price_ids)
    {

        if (!is_array($goods_sku_price_ids)) {
            $goods_sku_price_ids = explode(',', $goods_sku_price_ids);
        }
        $list = Db::name('goodssku_price')->where('id', 'in', $goods_sku_price_ids)->fieldRaw('goods_id,id')->select()->getarray();
        foreach ($list as $key => $goodssku_price) {
            if ($goodssku_price['goods_id'] != $goods_id) {
                throw new \Exception('商品id' . $goods_id . '没有该规格id' . $goodssku_price['id'], -1);
            }
        }
    }


    /**
     * 获取售后站信息
     * @param mixed $user
     * @return mixed
     */
    public function getAfterData($user)
    {
        $售后站 = null;
        if (isset($user['town_id']) && $user['town_id']) {
            $售后站 = Db::name('after_sales_site')->where('area_id', '=', $user['town_id'])->find();
        }

        if (!$售后站) {
            if (isset($user['district_id']) && $user['district_id']) {
                $售后站 = Db::name('after_sales_site')->where('area_id', '=', $user['district_id'])->find();
            }
        }

        if (!$售后站) {
            if (isset($user['city_id']) && $user['city_id']) {
                $售后站 = Db::name('after_sales_site')->where('area_id', '=', $user['city_id'])->find();
            }
        }

        if (!$售后站) {
            if (isset($user['province_id']) && $user['province_id']) {
                $售后站 = Db::name('after_sales_site')->where('area_id', '=', $user['province_id'])->find();
            }
        }

        if ($售后站) {
            $售后站['user'] = Db::name('user')->where('id', '=', $售后站['user_id'])->fieldRaw('nickname,mobile')->find();
        }

        return $售后站;
    }


    /**
     * ws成功
     * @param string $msg
     * @param mixed $data
     * @return array
     */
    public function ws_success($msg = '', $data = [], $type = 'auction', $code = 1)
    {
        return ['code' => $code, 'msg' => $msg, 'type' => $type, 'data' => $data];
    }

    /**
     * 错误
     * @param string $msg
     * @param mixed $data
     * @return array
     */
    public function ws_error($msg = '', $data = [], $type = 'auction', $code = -1)
    {
        return ['code' => $code, 'msg' => $msg, 'type' => $type, 'data' => $data];
    }

    /**
     * 获取月份的时间戳
     *
     * @param string $month 月
     * @return void
     */
    public function GetMonthTime($month)
    {
        $time = strtotime($month);
        $year = date('Y', $time);
        $month  = date('n', $time);
        $start_timestamp = strtotime("$year-$month-01"); // 获取该月的开始时间戳
        $end_timestamp = strtotime(date('Y-m-t 23:59:59', strtotime("$year-$month-01"))); // 获取该月的结束时间戳
        // var_dump(date('Y-m-d H:i:s',$start_timestamp),date('Y-m-d H:i:s',$end_timestamp));
        return [$start_timestamp, $end_timestamp];
    }


    public function UserSuretyReturn($val, $auction, $ps, $拍卖类型)
    {
        //没成功需要退回买家的保证金
        $tpmecm = new \ImiApp\ApiServer\Api\Controller\Tpmecms;
        $tpmecm->IncUserSurety($val['user_id'], $auction['buyer_surety'], $ps, $拍卖类型,  $val['id'], 'surety');
        Db::name('auction_offer')->where('id', '=', $val['id'])->update(['status' => '2', 'surety_status' => '2', 'surety_time' => time()]);
    }

    /**
     * 退回用户活动报名积分
     *
     * @param int $auction_id 活动id
     * @return void
     */
    public function ReturnUserAuctionEnrollScore($auction_id)
    {
        $list = Db::name('auction_enroll')->where('auction_id', '=', $auction_id)->where('return_status', '=', '1')->select()->getArray();
        if ($list) {
            foreach ($list as $key => $val) {
                if($val['score']>0){
                    $this->IncUserScore($val['user_id'], (float)$val['score'], '拍卖未成功', 23, $auction_id);
                    Db::name('auction_enroll')->where('id', '=', $val['id'])->update(['return_status' => '2', 'return_time' => time()]);
                }             
            }
        }
    }

    /**
     * 退回用户活动报名贝壳
     *
     * @param int $auction_id 活动id
     * @return void
     */
    public function ReturnUserAuctionEnrollShell($auction_id)
    {
        $list = Db::name('auction_enroll')->where('auction_id', '=', $auction_id)->where('return_status', '=', '1')->select()->getArray();
        if ($list) {
            foreach ($list as $key => $val) {
                if ($val['shell'] > 0) {
                    $this->IncUserShell($val['user_id'],(float) $val['shell'], '拍卖未成功', 23, $auction_id);
                    Db::name('auction_enroll')->where('id', '=', $val['id'])->update(['return_status' => '2', 'return_time' => time()]);
                }
            }
        }
    }


    //  /**
    //  * 退回用户活动报名贝壳
    //  *
    //  * @param int $auction_id 活动id
    //  * @return void
    //  */
    // public function ReturnUserAuctionEnrollScore($auction_id)
    // {
    //     $list = Db::name('auction_enroll')->where('auction_id', '=', $auction_id)->where('return_status', '=', '1')->select()->getArray();
    //     if ($list) {
    //         foreach ($list as $key => $val) {
    //             if($val['score']>0){
    //                 $this->IncUserScore($val['user_id'], $val['score'], '拍卖未成功', 23, $auction_id);
    //                 Db::name('auction_enroll')->where('id', '=', $val['id'])->update(['return_status' => '2', 'return_time' => time()]);
    //             }

    //         }
    //     }
    // }


    /**
     * 减少商品库存
     *
     * @param int $goods_sku_price_id 商品价格id
     * @param integer $num 数量默认1
     * @param string $ps 库存备注
     * @param int $order_id 订单id
     * @return void 
     */
    protected function DecGoodsStock($goods_sku_price_id, $num = 1, $ps = null, $order_id = null)
    {
        Db::name('goodssku_price')->where('id', '=', $goods_sku_price_id)->setFieldDec('stock', $num)->update();
        $data['status'] = '1'; //状态:1=减库存,2=加库存
        $data['ps'] = $ps;
        $data['num'] = $num;
        $data['order_id'] = $order_id;
        $data['goods_sku_price_id'] = $goods_sku_price_id;
        $data['time'] = time();
        $data['after'] =   Db::name('goodssku_price')->where('id', '=', $goods_sku_price_id)->value('stock');
        Db::name('goods_stock_log')->insert($data);
    }

    /**
     * 增加商品库存
     *
     * @param int $goods_sku_price_id 商品价格id
     * @param integer $num 数量默认1
     * @param string $ps 库存备注
     * @param int $order_id 订单id
     * @return void 
     */
    protected function IncGoodsStock($goods_sku_price_id, $num = 1, $ps = null, $order_id = null)
    {
        Db::name('goodssku_price')->where('id', '=', $goods_sku_price_id)->setFieldInc('stock', $num)->update();
        $data['status'] = '2'; //状态:1=减库存,2=加库存
        $data['ps'] = $ps;
        $data['num'] = $num;
        $data['order_id'] = $order_id;
        $data['goods_sku_price_id'] = $goods_sku_price_id;
        $data['time'] = time();
        $data['after'] =   Db::name('goodssku_price')->where('id', '=', $goods_sku_price_id)->value('stock');
        Db::name('goods_stock_log')->insert($data);
    }


    public function 拍卖报名总积分($auction_id){
        return Db::name('auction_enroll')->where('auction_id','=',$auction_id)->sum('score')??0;
    }

    public function 拍卖报名总贝壳($auction_id){
        return Db::name('auction_enroll')->where('auction_id','=',$auction_id)->sum('shell')??0;
    }

    public function 拍卖改价总贝壳($auction_id){
        return Db::name('auction_offer')->where('auction_id','=',$auction_id)->sum('shell')??0;
    }




    /**
     * 添加订单的快递
     *
     * @param array $data
     * @return void
     */
    public function AddOrderExpress($data)
    {

        // `user_id` int(11) NOT NULL COMMENT '用户',
        // `store_id` int(11) NOT NULL COMMENT '店铺',
        // `order_id` int(11) NOT NULL COMMENT '订单',
        // `order_item_id` int(11) DEFAULT NULL COMMENT '子订单',
        // `express_name` varchar(60) DEFAULT NULL COMMENT '快递公司',
        // `express_code` varchar(60) DEFAULT NULL COMMENT '公司编号',
        // `express_no` varchar(60) DEFAULT NULL COMMENT '快递单号',
        // `createtime` int(11) DEFAULT NULL COMMENT '添加时间',
        // `updatetime` int(11) DEFAULT NULL COMMENT '更新时间',
        // `status` enum('1','2','3') DEFAULT '1' COMMENT '状态:1=卖家正常发货,2=用户售后,3=卖家换货',
        Db::name('order_express')->insert($data);
    }


    /**
     * 增加订单商品库存
     *
     * @param int $order_id 订单id
     * @param string $ps 备注
     * @return void 
     */
    protected function IncOrderGoodsStock($order_id, $ps = null)
    {
        $list = Db::name('order_item')->where('order_id', '=', $order_id)->select()->getArray();
        foreach ($list as $key => $val) {
            $this->IncGoodsStock($val['goods_sku_price_id'], $val['goods_num'], $ps, $order_id);
        }
    }



    /**
     * 订单确认收货
     */
    public function orderItemConfirm($id)
    {
        //打款给卖家
        $where['id'] = $id;
        $order_item = Db::name('order_item')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->select()->get();

        //修改子订单状态
        Db::name('order_item')
            // ->whereEx($this->whereCom)
            ->whereEx($where)->update(['status' => '2']); //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成


        $order = Db::name('order')->where('id', '=', $order_item['order_id'])->find();

        //查询其他订单还有没有
        $NUM = Db::name('order_item')->where('order_id', '=', $order_item['order_id'])->where('status', '!=', '2')->count();

        if ($NUM < 1) {
            $res = Db::name('order')->where('id', '=', $order_item['order_id'])->where('status', '=', '2')->update(['status' => '2']); //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            if ($res) {
                //订单交易完成

            }
        }


        $queue2 = \Imi\Queue\Facade\Queue::getQueue('order');
        $message2 = new \Imi\Queue\Model\Message;
        //发布对列
        $message2->setMessage(json_encode(['type' => 'order_item_confirm', 'data' => $order_item], JSON_UNESCAPED_UNICODE));
        $queue2->push($message2);



        // //把订单里面的钱给商家
        // if ($order_item['item_pay_fee'] > 0)
        //     $this->IncStoreMoney($order_item['store_id'], $order_item['item_pay_fee'] * $order_item['goods_num'], '用户确认收货', CODE_用户确认收货, $id);

        // //把订单里面的积分给商家
        // if ($order_item['item_score_fee'] > 0)
        //     $this->IncStoreScore($order_item['store_id'], $order_item['item_score_fee'] * $order_item['goods_num'], '用户确认收货', CODE_用户确认收货, $id);

        // //把订单里面的贝壳给商家
        // if ($order_item['item_shell_fee'] > 0)
        //     $this->IncStoreShell($order_item['store_id'], $order_item['item_shell_fee'] * $order_item['goods_num'], '用户确认收货', CODE_用户确认收货, $id);


        // //判断分账状态 
        // // 如果是微信支付宝 分到对应的
        // switch ($order['pay_type']) {
        //     case 'wechat':
        //         # code...
        //         break;

        //         //阿里
        //     case 'alipay':
        //         # code...
        //         break;

        //         //钱包
        //     case 'wallet':
        //         # code...
        //         break;


        //     default:
        //         # code...
        //         break;
        // }


        // // 如果有积分把积分手续费给平台


        // //还要给上级提成
    }







    /**
     * 订单退款
     */
    public function storeOrderRefund($id)
    {
        //打款给买家
        $where['id'] = $id;
        $order_aftersale = Db::name('order_aftersale')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->select()->get();

        $order_item = Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->find();



        $order = Db::name('order')->where('id', '=', $order_item['order_id'])->find();
        $退运费 = 0;
        //查询其他订单还有没有
        $NUM = Db::name('order_item')->where('order_id', '=', $order_item['order_id'])->where('status', 'in', ['1', '2'])->count();
        var_dump('退运费' . $NUM);
        if ($NUM > 0) {
            // Db::name('order')->where('id', '=', $order_item['order_id'])->update(['status' => '2']);
        } else {
            //退运费判断
            if ($order['dispatch_amount'] > 0 && $order['refund_dispatch_status'] == '1') { // 退运费状态:1=未退,2=已退
                var_dump('实际退运费' . $order['dispatch_amount'], '售后订单id' . $id);
                $退运费 = (float)$order['dispatch_amount'];
                $this->IncUserMoney($order_aftersale['user_id'], (float)$order['dispatch_amount'], '未发货申请退运费', CODE_订单退款, $id);
                Db::name('order')->where('id', '=', $order_item['order_id'])->update(['refund_dispatch_status' => '2']);
            }
        }


        if ($order_aftersale['refund_score'] > 0) {
            $this->IncUserScore($order_aftersale['user_id'], (float)$order_aftersale['refund_score'], '未发货申请退款', CODE_订单退款, $id);

            if ($order_aftersale['refund_score'] > $order_item['score_fee']) {
                \Imi\Log\Log::error('退款积分' . $order_aftersale['refund_score'] . '大于支付积分' . $order_item['score_fee']);
            }

            Db::name('order_item')->where('id', '=', $order_item)->setFieldDec('score_fee', (float)$order_aftersale['refund_score']);
        }

        if ($order_aftersale['refund_shell'] > 0) {
            $this->IncUsershell($order_aftersale['user_id'], (float)$order_aftersale['refund_shell'], '未发货申请退款', CODE_订单退款, $id);

            if ($order_aftersale['refund_shell'] > $order_item['shell_fee']) {
                \Imi\Log\Log::error('退款贝壳' . $order_aftersale['refund_shell'] . '大于支付贝壳' . $order_item['shell_fee']);
            }

            Db::name('order_item')->where('id', '=', $order_item)->setFieldDec('shell_fee', (float)$order_aftersale['refund_shell']);
        }

        //如果是微信和支付宝支付,原路退回
        if ($order_aftersale['refund_fee'] > 0) {
            // $order
            $this->IncUserMoney($order_aftersale['user_id'], (float)$order_aftersale['refund_fee'], '未发货申请退款', CODE_订单退款, $id);

            if (($order_aftersale['refund_fee'] - $退运费) > $order_item['pay_fee']) {
                \Imi\Log\Log::error('退款金额' . $order_aftersale['refund_fee'] . '-退运费' . $退运费 . ' 大于支付金额' . $order_item['pay_fee']);
            }

            Db::name('order_item')->where('id', '=', $order_item)->setFieldDec('pay_fee', (float)$order_aftersale['refund_fee'] - $退运费);
        }


        // //把订单里面的钱给用户
        // if ($order_item['item_pay_fee'] > 0)
        //     $this->IncUserMoney($order_item['user_id'], $order_item['item_pay_fee'] * $order_item['goods_num'], '用户申请退款', CODE_订单退款, $id);

        // //把订单里面的积分给用户
        // if ($order_item['item_score_fee'] > 0)
        //     $this->IncUserScore($order_item['user_id'], $order_item['item_score_fee'] * $order_item['goods_num'], '用户申请退款', CODE_订单退款, $id);

        // //把订单里面的贝壳给用户
        // if ($order_item['item_shell_fee'] > 0)
        //     $this->IncUserShell($order_item['user_id'], $order_item['item_shell_fee'] * $order_item['goods_num'], '用户申请退款', CODE_订单退款, $id);


        $order_item = Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->find();
        //重新计算卖家
        if ($order_item['pay_fee'] > 0 || $order_item['score_fee'] > 0 || $order_item['shell_fee'] > 0)

            //判断分账状态 
            // 如果是微信支付宝 分到对应的
            switch ($order['pay_type']) {
                case 'wechat':
                    # code...
                    break;

                    //阿里
                case 'alipay':
                    # code...
                    break;

                    //钱包
                case 'wallet':
                    # code...
                    break;


                default:
                    # code...
                    break;
            }


        // 如果有积分把积分手续费给平台


        //还要给上级提成
    }



    /**
     * 
     *
     * @param int $id
     * @return void
     */
    public function itemIdGetOrder($id)
    {
        // Db::name('order_action')->insert($data);
    }

    /**
     * 获取订单信息
     *
     * @param int $id
     * @return array|null
     */
    public function getOrderById($id)
    {
        $order = Db::name('order')->where('id', '=', $id)->find();
        return $order;
    }


    /**
     * 获取子订单信息
     *
     * @param int $id
     * @return array|null
     */
    public function getOrderItemById($id)
    {
        $order = Db::name('order_item')->where('id', '=', $id)->find();
        return $order;
    }

    /**
     * 获取售后订单信息
     *
     * @param int $id
     * @return array|null
     */
    public function getOrderAftersaleById($id)
    {
        $order = Db::name('order_aftersale')->where('id', '=', $id)->find();
        return $order;
    }


    /**
     * 更新订单操作
     *
     * @param array $data
     * @return void
     */
    public function UpdateOrderAction($data)
    {
        Db::name('order_action')->insert($data);
    }


    /**
     * 获取最新商品日志id
     *
     * @param int $goods_id 商品id
     * @return void
     */
    public function getNewGoodslogId($goods_id)
    {
        return Db::name('goodslog')->where('id', '=', $goods_id)->orderRaw('goodslog_id desc')->value('goodslog_id');
    }

    /**
     * 获取店铺退款地址
     *
     * @param int $store_id
     * @return void
     */
    protected function GetStoreRefundAddrData($store_id)
    {
        $addr = Db::name('store_refund_addr')->where('store_id', '=', $store_id)->orderRaw('default_status desc')->find();
        return $addr;
    }

    /**
     * 获取地址信息🌍
     *
     * @param int $id 地址id
     * @return void
     */
    protected function GetAddrData($id)
    {
        return Db::name('addr')->where('id', '=', $id)->select()->get();
    }


    /**
     * 获取地址信息🌍
     *
     * @param int $id 地址id
     * @return void
     */
    protected function GetStoreAddrData($id)
    {
        return Db::name('store_refund_addr')->where('id', '=', $id)->select()->get();
    }

    /**
     * 获取店铺营业类型文字
     *
     * @param [type] $ids
     * @return void
     */
    protected function getGoodscateText($ids)
    {
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }
        $list = Db::name('goodscate')->whereIn('id', $ids)->column('name');
        return implode(',', $list);
    }



    /**
     * 获取店铺续费价格
     *
     * @param string $ltd_status  企业OR个人
     * @param int $set_id 角色id
     * @return void
     */
    protected  function getKeepStorePrice($ltd_status, $set_id = null)
    {
        // $str = [
        //     'set_id' => '类型id',
        //     'storeallset1' => '晋级条件(订单量)',
        //     'storeallset2' => '晋级条件(交易额)',
        //     'storeallset3' => '入驻积分奖励',
        //     'storeallset4' => '入驻费(元)',
        //     'storeallset5' => '次年续费',
        //     'storeallset6' => '店铺保证金(元)',
        //     'storeallset7' => '店铺晋升(元)',
        //     'storeallset8' => '网盘容量',
        //     'name' => '类型名',
        //     'val' => '设置'
        // ];
        $where['set_id'] = $set_id;


        //企业OR个人:1=个人,2=企业
        switch ($ltd_status) {
            case '1':
                $field = 'storeallset5';
                break;

            case '2':
                $field = 'storeallset5';
                break;
            default:
                # code...
                break;
        }
        $res = Db::name('storeallsetlist')->whereEx($where)->value($field);

        return $res;
    }


    /**
     * 获取店铺认证金额
     *
     * @param string $set_id 角色id
     * @return int
     */
    protected function GetStoreCaMoney($set_id)
    {
        $where['set_id'] = $set_id;
        $res = Db::name('storeallsetlist')->whereEx($where)->value('storeallset4');
        return $res;
    }

    /**
     * 获取店铺网盘容量
     *
     * @param string $set_id 角色id
     * @return int
     */
    protected function GetStoreNetdiskFilesize($set_id)
    {
        $where['set_id'] = $set_id;
        $res = Db::name('storeallsetlist')->whereEx($where)->value('storeallset8');
        return $res;
    }


    /**
     * 获取店铺保证金额
     *
     * @param string
     * @return int
     */
    protected function GetStoreSuretyMoney($set_id)
    {
        $where['set_id'] = $set_id;
        $res = Db::name('storeallsetlist')->whereEx($where)->value('storeallset6');
        return $res;
    }


    /**
     * 获取用户保证金额
     *
     * @param string
     * @return int
     */
    protected function GetUserSuretyMoney($set_id)
    {
        $where['set_id'] = $set_id;
        $res = Db::name('storeallsetlist')->whereEx($where)->value('storeallset6');
        return $res;
    }


    public function 扣除拍卖保证金的手续费给卖家($money){
        if($money>0){
            $money = $money *(1-0.05);
        }
        return $money;
    }




    /**
     * @param int $user_id 用户id
     * @param string $pay_type 支付类型surety=保证金,act_surety=活动保证金,score=积分,shell=贝壳,money=余额
     * @param string $amount 金额
     * @param string $type 类型
     * @param int $order_id 订单id
     * @param string $ps 备注
     * @param string $order 订单号
     * @param int $auction_id 拍卖id
     * @return void
     */
    public function IncUserFreeze($user_id, $pay_type, $amount, $type, $order_id = null, $ps = null, $order = null, $auction_id = null)
    {
        $data['user_id'] = $user_id;
        //类型:surety=保证金,act_surety=活动保证金,score=积分,shell=贝壳,money=余额
        switch ($pay_type) {
            case 'surety':
                $data['surety'] = $amount;
                break;
            case 'act_surety':
                $data['surety'] = $amount;
                break;
            case 'score':
                $data['score'] = $amount;
                break;
            case 'shell':
                $data['shell'] = $amount;
                break;
            case 'money':
                $data['money'] = $amount;
                break;
            default:
                # code...
                break;
        }
        $data['time'] = time();
        $data['type'] = $type; //类型
        $data['order_id'] = $order_id;
        $data['ps'] = $ps; //备注
        $data['user_status'] = 'user'; //用户类型:store=店铺,user=用户
        $data['order'] = $order;
        $data['auction_id'] = $auction_id;


        Db::name('freeze')->insert($data);
    }


    /**
     * @param int $user_id 用户id
     * @param string $pay_type 支付类型surety=保证金,act_surety=活动保证金,score=积分,shell=贝壳,money=余额
     * @param string $type 类型
     * @param int $order_id 订单id
     * @param string $ps 备注
     * @param string $order 订单号
     * @param string $ps 备注
     * int $auction_id 拍卖id
     * @return void
     */
    public function UnFreezeUser($user_id, $pay_type = null, $type = null,  $order_id = null, $ps = null, $auction_id = null)
    {
        $data['user_id'] = $user_id;
        //类型:surety=保证金,act_surety=活动保证金,score=积分,shell=贝壳,money=余额
        switch ($pay_type) {
            case 'surety':
                $field = 'surety';
                break;
            case 'act_surety':
                $field = 'surety';
                break;
            case 'score':
                $field = 'score';
                break;
            case 'shell':
                $field = 'shell';
                break;
            case 'money':
                $field = 'money';
                break;
            default:
                # code...
                break;
        }

        $data['type'] = $type; //类型
        $data['order_id'] = $order_id;

        $data['user_status'] = 'user'; //用户类型:store=店铺,user=用户
        if ($auction_id) {
            $data['auction_id'] = $auction_id;
        }


        $res = Db::name('freeze')->whereEx($data)->find();
        if ($res) {
            Db::name('freeze')->whereEx($data)->update(['pay_status' => '3', 'unfreeze_time' => time()]);
        } else {
            \Imi\Log\Log::error($ps . '解冻失败,未找到该记录' . json_encode($data, JSON_UNESCAPED_UNICODE));
        }
    }


    /**
     * @param int $store_id 店铺id
     * @param string $pay_type 支付类型surety=保证金,act_surety=活动保证金,score=积分,shell=贝壳,money=余额
     * @param string $amount 金额
     * @param string $type 类型
     * @param int $order_id 订单id
     * @param string $ps 备注
     * @param string $order 订单号
     * @param int $auction_id 拍卖id
     * @return void
     */
    public function IncStoreFreeze($store_id, $pay_type, $amount, $type, $order_id = null, $ps = null, $order = null, $auction_id = null)
    {
        $data['store_id'] = $store_id;
        //类型:surety=保证金,act_surety=活动保证金,score=积分,shell=贝壳,money=余额
        switch ($pay_type) {
            case 'surety':
                $data['surety'] = $amount;
                break;
            case 'act_surety':
                $data['surety'] = $amount;
                break;
            case 'score':
                $data['score'] = $amount;
                break;
            case 'shell':
                $data['shell'] = $amount;
                break;
            case 'money':
                $data['money'] = $amount;
                break;
            default:
                # code...
                break;
        }
        $data['time'] = time();
        $data['type'] = $type; //类型
        $data['order_id'] = $order_id;
        $data['ps'] = $ps; //备注
        $data['user_status'] = 'store'; //用户类型:store=店铺,user=用户
        $data['order'] = $order;
        $data['auction_id'] = $auction_id;

        Db::name('freeze')->insert($data);
    }




    /**
     * @param int $store_id 店铺id
     * @param string $pay_type 支付类型surety=保证金,act_surety=活动保证金,score=积分,shell=贝壳,money=余额
     * @param string $type 类型
     * @param string $order_id 订单id
     * @param string $ps 备注
     * @param string $order 订单号
     * @param string $ps 备注
     * @param int $auction_id 拍卖id
     * @return void
     */
    public function UnFreezeStore($store_id, $pay_type = null, $type = null,  $order_id = null, $ps = null, $auction_id = null)
    {
        $data['store_id'] = $store_id;
        //类型:surety=保证金,act_surety=活动保证金,score=积分,shell=贝壳,money=余额
        switch ($pay_type) {
            case 'surety':
                $field = 'surety';
                break;
            case 'act_surety':
                $field = 'surety';
                break;
            case 'score':
                $field = 'score';
                break;
            case 'shell':
                $field = 'shell';
                break;
            case 'money':
                $field = 'money';
                break;
            default:
                # code...
                break;
        }

        $data['type'] = $type; //类型
        $data['order_id'] = $order_id;

        $data['user_status'] = 'store'; //用户类型:store=店铺,user=用户
        if ($auction_id) {
            $data['auction_id'] = $auction_id;
        }


        $res = Db::name('freeze')->whereEx($data)->find();
        if ($res) {
            Db::name('freeze')->whereEx($data)->update(['pay_status' => '3', 'unfreeze_time' => time()]);
        } else {
            \Imi\Log\Log::error($ps . '解冻失败,未找到该记录' . json_encode($data, JSON_UNESCAPED_UNICODE));
        }
    }

    // /**
    //  * 获取店铺认证金额
    //  *
    //  * @param string $ltd_status 企业OR个人:1=个人,2=企业
    //  * @return int
    //  */
    // protected function GetStoreCaMoney($ltd_status)
    // {
    //     switch ($ltd_status) {
    //         case '1':
    //             return config('personal_store');
    //             break;

    //         case '2':
    //             return config('enterprise_store');
    //             break;
    //         default:
    //             return 99999;
    //             break;
    //     }
    // }

    /**
     * 获取店铺信息
     * 
     * @param int $id 店铺id
     * @return void
     */
    public function getStoreData2($id)
    {
        //可缓存
        return Db::name('store')->where('id', '=', $id)->fieldRaw('name,logo_image,id')->find();
    }

    /**
     * 获取店铺信息
     * 
     * @param int $id 店铺id
     * @return void
     */
    public function getStoreData3($id)
    {
        //可缓存
        $store = Db::name('store')
            ->where('id', '=', $id)
            ->fieldRaw('name,logo_image,surety,credit,good,comments,ltdtype_status,ltd_status,city_switch')
            ->find();
        $store['good_ratio'] = 100; //好评率
        if ($store['comments'] > 0) {
            $store['good_ratio'] = round($store['good'] / $store['comments'] * 100, 0);
        }
        return $store;
    }

    /**
     * 获取店铺信息(收藏
     * 
     * @param int $id 店铺id
     * @return void
     */
    public function getStoreData4($id)
    {
        //可缓存
        $store = Db::name('store')->where('id', '=', $id)->fieldRaw('city_id,area_id,name,logo_image,id,work_date,work_time,lat,lng,ltdtype_status,ltd_status,addr,goodscate_text,goodscate_ids')->find();
        if (!$store) {
            return $this->error('店铺不存在', 'getStoreData4_店铺id:' . $id);
        }
        if (!$store['city_id']) {
            $area = $this->GetAreaAllData($store['area_id']);
            if ($area) {
                Db::name('store')->where('id', '=', $store['id'])->update($area);
                $store['city_id'] = $area['city_id'];
            }
        }
        $store['city'] = $this->GetAreaDataCom($store['city_id'])['name'];

        if (!$store['goodscate_text']) {
            $store['goodscate_text'] = $this->getGoodscateText($store['goodscate_ids']);
            if ($store['goodscate_text'])
                Db::name('store')->where('id', '=', $store['id'])->update(['goodscate_text' => $store['goodscate_text']]);
        }


        return $store;
    }


    /**
     * 获取店铺信息
     * 
     * @param int $id 店铺id
     * @return void
     */
    public function getStoreData5($id)
    {
        //可缓存
        return Db::name('store')->where('id', '=', $id)->fieldRaw('name,logo_image,mobile,id')->find();
    }



    /**
     * 获取店铺信息
     * 
     * @param int $id 店铺id
     * @return void
     */
    public function getStoreData6($id)
    {
        //可缓存
        return Db::name('store')->where('id', '=', $id)->fieldRaw('name,logo_image,mobile,id')->find();
    }





    /**
     * 获取商品店铺id
     *
     * @param [type] $store_id
     * @return void
     */
    public function GetStoreToday($store_id)
    {
        // return Db::name('goods')->where('public_id', '=', $store_id)->where('viewstatus_id','=',STORE)->value('store_id');
    }

    /**
     * 获取商品店铺id
     *
     * @param [type] $goods_id
     * @return void
     */
    public function GetGoodsStoreId($goods_id)
    {
        return Db::name('goods')->where('id', '=', $goods_id)->value('store_id');
    }



    /**
     * 是否是店铺
     *
     * @param int $user_id 用户id
     * @return boolean
     */
    public function isStore($user_id = null)
    {
        if (!$user_id)
            $user_id = $this->auth->user()->id;
        $store = Db::name('store')->where('user_id', '=', $this->auth->user()->id)->find();
        if ($store)
            return $store;
        // $this->error('非店铺', $user_id, CODE_非店铺);
        throw new \Exception('非店铺', CODE_非店铺);
        return false;
    }



    //  _____      __  __         ____ __  __ ____  
    // |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
    //   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
    //   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
    //   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/04/08
    //      |_|                                         | TpMeCMS

    /**
     * 服务费计算
     * 
     * @param integer $total_amount 订单总金额
     * @param integer $total_fee 支付总金额
     * @param integer $shell 贝壳
     * @param integer $score 积分
     * @param integer $coupon_fee 优惠券总金额
     * @param integer $platform_coupon_fee 平台优惠券金额
     * @return void
     */
    public function ServiceFeeCount($total_amount = 0, $total_fee = 0, $shell = 0, $score = 0, $coupon = 0, $coupon_fee = 0, $platform_coupon_fee = 0)
    {
    }

    /**
     * 获取优惠券
     *
     * @param int $id 优惠券
     * @return void
     */
    public function getCoupon($id)
    {
        $coupons = Db::name('coupons')->where('id', '=', $id)->find();
        if (!$coupons) {
            return $this->error('没有该优惠券');
        }
        return $coupons;
    }

    /**
     * 获取最大的店铺优惠券
     *
     * @param int $goods_money 商品总价格
     * @param int $user_id 用户id
     * @param int $store_id 店铺id
     * @return void
     */
    public function getMaxStoreCoupon($goods_money, $user_id, $store_id)
    {
        $coupons_ids = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('store_id', '=', $store_id)->where('user_id', '=', $user_id)->column('coupons_id');
        $max = 0;
        $coupon = false;

        if ($coupons_ids) {
            $list = Db::name('coupons')
                ->whereIn('id',  $coupons_ids)
                ->where('scene_type','=','current')
                ->where('type_status', '!=', '4') //'类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷',
                ->whereIn('scene', ['current', 'direct'])
                ->fieldRaw('name,type,id,man,jian,store_id,goods_ids,type_status')
                ->whereIsNull('goods_ids')
                ->select()
                ->getArray();

            foreach ($list as $key => $val) {
                if ($val['man'] <= $goods_money) {
                    if ($max < $val['jian']) {
                        $max = $val['jian'];
                        $coupon = $val;
                    }
                }
            }
        }
        return $coupon;
    }


    /**
     * 获取最大的店铺优惠券满减和商品券
     *
     * @param int $goods_money 商品总价格
     * @param int $user_id 用户id
     * @param int $store_id 店铺id
     * @return void
     */
    public function getMaxStoreCoupon1_6($goods_money, $user_id, $store_id)
    {
        $coupons_ids = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('store_id', '=', $store_id)->where('user_id', '=', $user_id)->column('coupons_id');
        $max = 0;
        $coupon = false;

        if ($coupons_ids) {
            $list = Db::name('coupons')
                ->whereIn('id',  $coupons_ids)
                ->where('scene_type','=','current')
                ->where('type_status', '!=', '4') //'类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷',
                ->whereIn('scene', ['current', 'direct'])
                ->fieldRaw('name,type,id,man,jian,store_id,goods_ids,type_status')
                ->whereIsNull('goods_ids')
                ->select()
                ->getArray();

            foreach ($list as $key => $val) {
                if ($val['man'] <= $goods_money) {
                    if ($max < $val['jian']) {
                        $max = $val['jian'];
                        $coupon = $val;
                    }
                }
            }
        }
        return $coupon;
    }



    /**
     * 获取最大的商品优惠券
     *
     * @param int $user_id 用户id
     * @param array $goods_ids 商品ids
     * @return void
     */
    public function getMaxStoreGoodsCoupon($user_id, $goods_ids = null, $store_id = null)
    {

        var_dump('goods_ids', $goods_ids);
        if ($store_id)
            $where['store_id'] = $store_id;

        $where['user_id'] = $user_id;

        $coupons_ids = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->whereEx($where)->column('coupons_id');
        $max = 0;
        $coupon = false;

        if ($coupons_ids) {
            $list = Db::name('coupons')
                ->whereIn('id',  $coupons_ids)
                ->where('scene_type','=','current')
                ->whereIsNotNull('goods_ids')
                ->where('type_status', '=', '6')
                ->fieldRaw('name,type,id,man,jian,store_id,goods_ids,type_status')
                ->select()
                ->getArray();

            var_dump('coupons', $list);

            foreach ($list as $key => $val) {
                $arr = explode(',', $val['goods_ids']);

                foreach ($arr as $key2 => $goods_id) {
                    if (in_array($goods_id, $goods_ids)) {
                        $val['goods_id'] = $goods_id;
                        if ($max < $val['jian']) {
                            $max = $val['jian'];
                            $coupon = $val;
                        }
                    }
                }
            }
        }
        if ($coupon)
            $coupon['jian'] = (float)$coupon['jian'];
        var_dump('getMaxStoreGoodsCoupon', $coupon);
        return $coupon;
    }


    /**
     * 获取最大的商品优惠券2
     *
     * @param int $user_id 用户id
     * @param array $goods_ids 商品ids
     * @return void
     */
    public function getMaxStoreGoodsCoupon2($user_id, $goods_list = null, $store_id = null, $店铺金额占比 = null, $_该店铺商品扣除积分和贝壳后的金额_ = null)
    {

        // var_dump('goods_ids',$goods_ids);
        // if($store_id)
        // $where['store_id'] = $store_id;
        if (!$_该店铺商品扣除积分和贝壳后的金额_) {
            return false;
        }


        $coupons_ids = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('store_id', '=', $store_id)->where('user_id', '=', $user_id)->column('coupons_id');
        $max = 0;
        $coupon = false;
        var_dump('$店铺金额占比', $店铺金额占比);
        if ($coupons_ids) {
            foreach ($goods_list as $key => $val) {
                $goods_id = $val['goods_id'];
                if ($店铺金额占比 > 0) {
                    $goods_price = $val['price'] * $val['num'] * $店铺金额占比;
                } else {
                    $goods_price = $val['price'] * $val['num'];
                }
                // $goods_price = $val['price'] * $val['num']; //system_goods_money
                $temp = Db::name('coupons')
                    ->whereIn('id',  $coupons_ids)
                    ->where('scene_type','=','current')
                    ->where('man', '<=', $goods_price)
                    ->where('goods_ids', '=', $goods_id)
                    ->fieldRaw('name,type,id,man,jian,store_id,goods_ids,type_status')
                    ->orderRaw('jian desc')
                    ->find();
                // var_dump('最大的商品优惠券222', $temp, $goods_price, $val);
                if ($max < $temp['jian']) {
                    $max = $temp['jian'];
                    $coupon = $temp;
                    $coupon['goods_id'] = $goods_id;
                }
            }
        }
        // var_dump('最大的商品优惠券2', $coupon);
        return $coupon;




    }


    /**
     * 使用优惠券
     *
     * @param int $coupons_id 优惠券id
     * @param int $user_id 用户id
     * @param array $order_id 订单id
     * @return void
     */
    public function useCoupon($coupons_id, $user_id, $order_id = null)
    {

        var_dump('useCoupon', $coupons_id, $user_id, $order_id);
        $user_coupons = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('coupons_id', '=', $coupons_id)->where('user_id', '=', $user_id)->orderRaw('end_time asc')->find();
        if ($user_coupons) {
            Db::name('user_coupons')->where('id', '=', $user_coupons['id'])->update(['status' => '2', 'order_id' => $order_id, 'usetime' => time()]);
        } else {

            return $this->error('无优惠券', $coupons_id);
        }
        return null;
    }






    /**
     * 获取店铺商品优惠券是否可以使用
     *
     * @param int $coupons_id 优惠券id
     * @param int $user_id 用户id
     * @param array $goods_ids 商品ids
     * @return void
     */
    public function getStoreGoodsCouponIsUse($coupons_id, $user_id, $goods_ids = null)
    {

        var_dump('___________-————————————————————————————————————-getStoreGoodsCouponIsUse', $coupons_id, $goods_ids);
        $user_coupons = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('coupons_id', '=', $coupons_id)->where('user_id', '=', $user_id)->find();
        if ($user_coupons) {


            $coupons = Db::name('coupons')->where('id', '=',  $coupons_id)->where('scene_type','=','current')->fieldRaw('name,type,id,man,jian,store_id,goods_ids,type_status')->find();
            $arr = explode(',', $coupons['goods_ids']);

            foreach ($arr as $key2 => $goods_id) {
                if (in_array($goods_id, $goods_ids)) {
                    $coupon['goods_id'] = $goods_id;
                    return $coupons;
                }
            }
        } else {
            if (config('app_coupons_tip_error'))
                // return $this->error('该商品优惠券无法使用或已过期', $coupons_id);
                throw new \Exception('该商品优惠券无法使用A', -1);
        }
        // var_dump('___________-该商品优惠券无法使用'.$coupons_id);
        if (config('app_coupons_tip_error'))
            // return $this->error('该商品优惠券无法使用', $coupons_id);
            throw new \Exception('该商品优惠券无法使用B', -1);

        return null;
    }

    /**
     * 获取店铺优惠券是否可以使用
     *
     * @param int $coupons_id 优惠券id
     * @param int $goods_money 商品总价格
     * @param int $user_id 用户id
     * @param int $store_id 店铺id
     * @return void
     */
    public function getStoreCouponIsUse($coupons_id, $goods_money, $user_id, $store_id)
    {
        $user_coupons = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('coupons_id', '=', $coupons_id)->where('store_id', '=', $store_id)->where('user_id', '=', $user_id)->find();
        if ($user_coupons) {


            $coupons = Db::name('coupons')->where('id', '=',  $coupons_id)->where('scene_type','=','current')->fieldRaw('name,type,id,man,jian,store_id,type_status')->find();
            if ($coupons['type_status'] == '6') {
                if (config('app_coupons_tip_error')) {
                    throw new \Exception('该优惠券是商品优惠券', -1);
                    // return $this->error('该优惠券是商品优惠券', $coupons_id);
                } else {
                }
                var_dump('该优惠券是商品优惠券,不能店铺券');
            } else {
                if ($coupons['man'] <= $goods_money) {
                    return $coupons;
                } else {
                    if (config('app_coupons_tip_error'))
                        // return $this->error('金额不够满减', $coupons);
                        throw new \Exception('金额不够满减', -1);
                }
            }
        } else {
            if (config('app_coupons_tip_error'))
                throw new \Exception('该店铺优惠券无法使用或已过期', -1);
            // return $this->error('该店铺优惠券无法使用或已过期', $coupons_id);
        }
        return null;
    }




    /**
     * 获取最大的平台优惠券
     *
     * @param int $goods_money 商品总价格
     * @param int $user_id 用户id
     * @return void
     */
    public function getMaxCoupon($goods_money, $user_id)
    {
        $coupons_ids = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('store_id', '=', 0)->where('user_id', '=', $user_id)->column('coupons_id');
        $max = 0;
        $coupon = false;
        if ($coupons_ids) {
            $list = Db::name('coupons')
                ->whereIn('id',  $coupons_ids)
                ->where('scene_type','=','current')
                ->fieldRaw('name,type,id,man,jian,store_id,type_status')
                ->select()
                ->getArray();

            foreach ($list as $key => $val) {
                if ($val['man'] <= $goods_money) {
                    if ($max < $val['jian']) {
                        $max = $val['jian'];
                        $coupon = $val;
                    }
                }
            }
        }
        return $coupon;
    }


    /**
     * 获取平台优惠券是否使用
     *
     * @param int $coupons_id 优惠券id
     * @param int $goods_money 商品总价格
     * @param int $user_id 用户id
     * @return void
     */
    public function getCouponIsUse($coupons_id, $goods_money, $user_id)
    {
        $coupons = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('coupons_id', '=', $coupons_id)->where('store_id', '=', 0)->where('user_id', '=', $user_id)->find();
        if ($coupons) {
            $coupons = Db::name('coupons')->where('scene_type','=','current')->where('id', '=', $coupons_id)->find();
            if ($coupons['man'] <= $goods_money) {
                return $coupons;
            } else {
                if (config('app_coupons_tip_error'))
                    throw new \Exception('平台优惠券,金额不够满减',-1);
                    // return $this->error('金额不够满减', $coupons);
            }
        } else {
            if (config('app_coupons_tip_error'))
                throw new \Exception('该平台优惠券无法使用或已过期',-1);
                // return $this->error('该平台优惠券无法使用或已过期', $coupons_id);
        }
    }

    /**
     * 获取平台拍卖服务费优惠券是否使用
     *
     * @param int $coupons_id 优惠券id
     * @param int $goods_money 商品总价格
     * @param int $user_id 用户id
     * @return void
     */
    public function getSysCouponAuctionServerIsUse($coupons_id, $goods_money, $user_id)
    {
        $coupons = Db::name('user_coupons')->where('end_time', '>', time())->where('status', '=', '1')->where('coupons_id', '=', $coupons_id)->where('store_id', '=', 0)->where('user_id', '=', $user_id)->find();
        if ($coupons) {
            $coupons = Db::name('coupons')->where('scene_type','=','auction_server')->where('id', '=', $coupons_id)->find();
            if ($coupons['man'] <= $goods_money) {
                return $coupons;
            } else {
                if (config('app_coupons_tip_error'))
                    throw new \Exception('平台拍卖服务费优惠券,金额不够满减',-1);
                    // return $this->error('金额不够满减', $coupons);
            }
        } else {
            if (config('app_coupons_tip_error'))
                throw new \Exception('该平台拍卖服务费优惠券无法使用或已过期',-1);
                // return $this->error('该平台优惠券无法使用或已过期', $coupons_id);
        }
    }

    /**
     * 获取角色名
     *
     * @param int $id
     * @return void
     */
    public function getSetName($id)
    {
        return Db::name('set')->where('id', '=', $id)->value('name');
    }

    /**
     * 用户可使用积分
     * 
     * @param int $money 需支付金额
     * @param int $set_id 角色id
     * @param int $user_id 用户id
     * @return float
     */
    public function UserUsableScore($money, $set_id = null, $user_id = null)
    {
        if (!$set_id)
            $set_id = $this->auth->user()->set_id;
        if (!$user_id)
            $user_id = $this->auth->user()->id;

        if ($set_id < 1 || $set_id > 7) {
            return $this->error('用户可使用积分,角色错误', $set_id);
        }
        if ($money < 0) {
            return $this->error('用户可使用积分金额错误', $money);
        }
        $ratio = $this->GetSetserveruserVal($user_id, $set_id, 2);
        var_dump('可使用积分比例', $ratio);
        $score = $money * $ratio / 100;
        return $score;
    }


    /**
     * 获取用户积分服务费(元)
     * 
     * @param int $score 需支付积分
     * @param int $set_id 角色id
     * @param int $user_id 用户id
     * @return float
     */
    public function UserPayScoreServerFee($score = 0, $set_id = null, $user_id = null)
    {
        if (!$set_id)
            $set_id = $this->auth->user()->set_id;
        if (!$user_id)
            $user_id = $this->auth->user()->id;

        if ($set_id < 1 || $set_id > 7) {
            return $this->error('用户积分服务费,角色错误', $set_id);
        }
        if ($score < 0) {
            return $this->error('用户积分服务费积分错误', $score);
        }
        $ratio = $this->GetSetserveruserVal($user_id, $set_id, 3);
        $money = $score * $ratio / 100;
        return $money;
    }

    /**
     * 获取商品数组总运费
     *
     * @param array $ids 商品ids 
     * @param int $addr_id 地址 
     * @return float
     */
    public function GetGoodsIdsDispatchAmount($ids, $addr_id = null)
    {
        var_dump($ids, 'addrid' . $addr_id);
        if (!$addr_id)
            return 0;
        $max = 0;
        $包邮 = false;
        //先获取商品的所有模版
        if (!is_array($ids))
            $ids = explode(',', $ids);
        $dispatch_ids = Db::name('goods')->whereIn('id', $ids)->column('dispatch_ids');



        if ($dispatch_ids) {

            foreach ($dispatch_ids as $key => $t_ids) {
                if (!$t_ids) {
                    $包邮 = true;
                    // var_dump('包邮');
                }
            }

            $addr = $this->GetAddrData($addr_id);

            $list = Db::name('dispatch')->whereIn('id', $dispatch_ids)->select()->getArray();
            // var_dump($list,$包邮);
            //总模版
            if ($list && !$包邮) {
                foreach ($list as $key => $val) {
                    //子模版
                    if ($val['type'] == 'express') {
                        $express_ids = explode(',', $val['type_ids']);
                        // Db::name('dispatch_express')->whereIn('id',$express_ids)->where()->max('first_price');
                        //找乡镇
                        // var_dump($express_ids,$addr);
                        $price = Db::name('dispatch_express')->whereIn('id', $express_ids)->whereRaw('FIND_IN_SET(' . $addr['town_id'] . ',town_ids)')->max('first_price');
                        if ($price) {
                            $max = max([$max, $price]);
                        } else {
                            var_dump('qu');
                            //找区
                            $price = Db::name('dispatch_express')->whereIn('id', $express_ids)->whereRaw('FIND_IN_SET(' . $addr['district_id'] . ',district_ids)')->max('first_price');
                            if ($price) {
                                $max = max([$max, $price]);
                            } else {
                                //找市
                                $price = Db::name('dispatch_express')->whereIn('id', $express_ids)->whereRaw('FIND_IN_SET(' . $addr['city_id'] . ',city_ids)')->max('first_price');
                                if ($price) {
                                    $max = max([$max, $price]);
                                } else {
                                    //找省

                                    $price = Db::name('dispatch_express')->whereIn('id', $express_ids)->whereRaw('FIND_IN_SET(' . $addr['province_id'] . ',province_ids)')->max('first_price');
                                    if ($price) {
                                        $max = max([$max, $price]);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                $包邮 = true;
            }
        }

        return $max;
        // Db::name('goods')->whereIn('id',$ids)->where('')
    }


    public function 获取商品规格列表ids($goods_id){
        $ids = Db::name('goodssku_price')->where('goods_id','=',$goods_id)->column('id');
        var_dump('获取商品'.$goods_id.'规格列表ids',$ids);
        return implode(',',$ids);
    }


    /**
     * 获取运费模版的运费
     *
     * @param int $dispatch_ids 模版ids
     * @param int $addr_id 地址
     * @return float
     */
    public function GetDispatchAmount($dispatch_ids=null, $addr_id = null)
    {

        if (!$addr_id | !$dispatch_ids)
            return 0;
        $max = 0;
        $包邮 = false;
        $dispatch_ids = explode(',', $dispatch_ids);

//            foreach ($dispatch_ids as $key => $t_ids) {
//                if (!$t_ids) {
//                    $包邮 = true;
//                    // var_dump('包邮');
//                }
//            }

            $addr = $this->GetAddrData($addr_id);
            if(!$addr)
                return 0;
//                throw  new \Exception("没有该地址",-1);


            $list = Db::name('dispatch')->whereIn('id', $dispatch_ids)->select()->getArray();

//             var_dump($list,$包邮);
            //总模版
            if ($list && !$包邮) {
                foreach ($list as $key => $val) {
                    //子模版
                    if ($val['type'] == 'express') {
                        if(!$val['type_ids']){
                            continue;
                        }
                        $express_ids = explode(',', $val['type_ids']);
                        // Db::name('dispatch_express')->whereIn('id',$express_ids)->where()->max('first_price');
                        //找乡镇
//                         var_dump($express_ids,$addr);
                        $price = Db::name('dispatch_express')->whereIn('id', $express_ids)->whereRaw('FIND_IN_SET(' . $addr['town_id'] . ',town_ids)')->whereIsNotNull('town_ids')->max('first_price');
                        if ($price) {
                            $max = max([$max, $price]);
                        } else {
//                            var_dump('qu');
                            //找区
                            $price = Db::name('dispatch_express')->whereIn('id', $express_ids)->whereRaw('FIND_IN_SET(' . $addr['district_id'] . ',district_ids)')->whereIsNotNull('district_ids')->max('first_price');
                            if ($price) {
                                $max = max([$max, $price]);
                            } else {
                                //找市
                                $price = Db::name('dispatch_express')->whereIn('id', $express_ids)->whereRaw('FIND_IN_SET(' . $addr['city_id'] . ',city_ids)')->whereIsNotNull('city_ids')->max('first_price');
                                if ($price) {
                                    $max = max([$max, $price]);
                                } else {
                                    //找省

                                    $price = Db::name('dispatch_express')->whereIn('id', $express_ids)->whereRaw('FIND_IN_SET(' . $addr['province_id'] . ',province_ids)')->whereIsNotNull('province_ids')->max('first_price');
                                    if ($price) {
                                        $max = max([$max, $price]);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                $包邮 = true;
            }


        return $max;
        // Db::name('goods')->whereIn('id',$ids)->where('')
    }



    /**
     * 获取用户服务费比例设置
     *
     * @param int $user_id 用户id
     * @param int $set_id 角色
     * @param int $service_ratio_id 服务比例id1=支付现金贝壳返现%,2=积分最多可用%,3=积分服务费%,4=拍卖服务费%,5=立即买单 限额/日(元),6=提现服务费%,7=贝壳转移服务费%
     * @return float
     */
    public function GetSetserveruserVal($user_id, $set_id, $service_ratio_id)
    {
        $where['set_id'] = $set_id;
        $where['service_ratio_id'] = $service_ratio_id;
        $where['user_id'] = $user_id;

        $val = Db::name('setserveruser')->whereEx($where)
            // ->cache($this->db_cache_set)
            ->value('val');
        if (!$val) {
            $where['user_id'] = 1; //平台默认参数
            $val = Db::name('setserveruser')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->value('val');
        }
        return $val;
    }

    /**
     * 获取店铺的上级用户
     *
     * @param int $store_id
     * @return array|bool
     */
    public function getStorePidUser($store_id)
    {
        $store = Db::name('store')->where('id', '=', $store_id)->find();
        $user = false;
        if ($store['pid'] > 0) {
            $user = Db::name('user')->where('id', '=', $store['pid'])->find();
        }
        return $user;
    }

    /**
     * 获取店铺的上级用户
     *
     * @param int $store_id
     * @return array|bool
     */
    public function getStorePidUser2($store_id)
    {
        $store = Db::name('store')->where('id', '=', $store_id)->find();
        $user = false;
        if ($store['pid'] > 0) {
            $user = Db::name('user')->where('id', '=', $store['pid'])->find();
        }
        $user['self_set_id'] = $store['set_id'];
        return $user;
    }


    /**
     * 获取用户的上级用户
     *
     * @param int $user_id
     * @return array|bool
     */
    public function getUserPidUser($user_id)
    {
        $user = Db::name('user')->where('id', '=', $user_id)->fieldRaw('id,set_id,pid')->find();
        $puser = false;
        if ($user['pid'] > 0) {
            $puser = Db::name('user')->where('id', '=', $user['pid'])->fieldRaw('id,set_id,pid')->find();
        }

        $puser['self_set_id'] = $user['set_id'];
        return $puser;
    }





    /**
     * 获取间接辅导员
     *
     * @param int $user_id  用户id
     * @return void
     */
    public function getJianJieFuDaoYuan($user_id)
    {

        if ($user_id) {
            $user = Db::name('user')->where('id', '=', $user_id)->find();
            if ($user['guidance'] == '2') { //辅导员:0=未知,1=非辅导员,2=辅导员
                return $user;
            } else {
                if ($user['pid'] > 0) {
                    // $userp = Db::name('user')->where('id', '=',$user['pid'])->find();
                    $user = $this->getJianJieFuDaoYuan($user['pid']);
                } else {
                    return false;
                }
            }
        }
        return $user;
    }



    /**
     * 获取运营中心比例设置
     *
     * @param int $run_id 用户id
     * @param int $set_id 角色
     * @param int $field direct1=销售直推%,indirect1=销售间接%,direct2=参与直推%,indirect2=参与间接%
     * @return float
     */
    public function GetRunCommissionSetVal($run_id, $set_id, $field = null)
    {
        if ($set_id == 7) {
            //售后站
            $run_id = 1;
        }
        $where['set_id'] = $set_id;
        // $where['service_ratio_id'] = $service_ratio_id;
        $where['run_id'] = $run_id;


        $val = Db::name('run_commission_set')->whereEx($where)
            // ->cache($this->db_cache_set)
            ->find();
        if (!$val) {
            $where['run_id'] = 1; //平台默认参数
            $val = Db::name('run_commission_set')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->find();
        }
        if (!$field)
            return $val;

        return $val[$field];
    }


    public function AddCommission($val)
    {
        $data['order_total_id'] =  isset($val['order_total_id']) ? $val['order_total_id'] : '';
        $data['order_id'] =  isset($val['order_id']) ? $val['order_id'] : '';
        $data['order_item_id'] =  isset($val['order_item_id']) ? $val['order_item_id'] : '';
        $data['oper_type'] =  $val['oper_type']; //提成人类型:user=买家,store=卖家,admin=管理,system=平台,after=售后站,run=运营中心
        $data['oper_id'] = $val['oper_id']; // 提成人id
        $data['money_type'] = $val['money_type']; //金额类型:money=钱,shell=贝壳,score=积分
        $res = Db::name('commission')->whereEx($data)->find();
        if (!$res) {
            $data['money'] = $val['money'];
            $data['time'] = time();
            $data['low_id'] = isset($val['low_id']) ? $val['low_id'] : '';

            $data['ps'] = $val['ps'];
            $data['freeze_status'] = '2';
            Db::name('commission')->insert($data);
            // \Imi\Log\Log::info('买家下单,现金支付返贝壳' . $data['money'] . '=' . $val['total_fee'] . '*' . $现金服务费比例 . '*' . $goods['goods_service_ratio']);
        }
    }


    /**
     * 获取商品信息
     *
     * @param int $goods_id
     * @return void
     */
    public function GetGoodsDataById($goods_id)
    {
        return Db::name('goods')->where('id', '=', $goods_id)->find();
    }

    /**
     * 获取商品简单信息
     *
     * @param int $goods_id
     * @return void
     */
    public function GetGoodsShortDataById($goods_id)
    {
        return Db::name('goods')->where('id', '=', $goods_id)->fieldRaw('title,status,goodscate_ids,image,price,is_sku,dispatch_type,dispatch_ids,goods_service_ratio,goodsbrand_id')->find();
    }


    /**
     * 获取商品简单信息2
     *
     * @param int $goods_id
     * @return void
     */
    public function GetGoodsShortDataById2($goods_id)
    {
        return Db::name('goods')->where('id', '=', $goods_id)->fieldRaw('title,status,goodscate_ids,image,price,is_sku,dispatch_type,dispatch_ids,goods_service_ratio,goodsbrand_id')->find();
    }

    /**
     * 获取商品简单信息2
     *
     * @param int $goods_id
     * @return void
     */
    public function GetGoodsShortDataByIdAuction($goods_id)
    {
        return Db::name('goods')->where('id', '=', $goods_id)->fieldRaw('title,status,goodscate_ids,image,images,content_images,price,is_sku,dispatch_type,dispatch_ids,goods_service_ratio,goodsbrand_id,new_status,sales,send_addr,content,params')->find();
    }

    /**
     * 获取商品简单信息3
     *
     * @param int $goods_id
     * @return void
     */
    public function GetGoodsShortDataById3($goods_id)
    {
        return Db::name('goods')->where('id', '=', $goods_id)->fieldRaw('image,id')->find();
    }

    /**
     * 获取商品简单信息4
     *
     * @param int $goods_id
     * @return void
     */
    public function GetGoodsShortDataById4($goods_id)
    {
        return Db::name('goods')->where('id', '=', $goods_id)->fieldRaw('image,id,title')->find();
    }

    /**
     * 获取店铺商品服务费比例
     * 
     * @param array $goods 商品
     * @param int $set_id 角色id
     * @param int $store_id 店铺id
     * @return float
     */
    public function StoreGetGoodsMoneyServerRatio($goods, $set_id = null, $store_id = null)
    {
        $goodscate_id = $goods['goodscate_ids'];
        $goodsbrand_id = $goods['goodsbrand_id'];
        if (!$set_id)
            $set_id = $this->auth->user()->set_id;
        if (!$store_id)
            return $this->error('缺少店铺参数');

        if ($set_id < 10 || $set_id > 20) {
            return $this->error('店铺商品服务费,角色错误', $set_id);
        }
        if ($goodscate_id < 0) {
            return $this->error('店铺商品服务费商品分类错误', $goodscate_id);
        }
        $goodscate_ratio = Db::name('goodscate')->where('id', '=', $goodscate_id)
            // ->cache($this->db_cache_set)
            ->value('goodscate_ratio'); //分类比例
        $goodsbrand_ratio = Db::name('goodsbrand')->where('id', '=', $goodsbrand_id)->where('deletetime', '=', '')
            // ->cache($this->db_cache_set)
            ->value('goodsbrand_ratio'); //品牌比例

        switch ($goods['type']) {
            case 'normal':
                //实物
                $ratio = $this->GetSetserverstoreVal($store_id, $set_id, 8); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
                break;

            default:
                $ratio = $this->GetSetserverstoreVal($store_id, $set_id, 9); //9=现金服务费%(服务
                break;
        }
        $res = $goodscate_ratio * $ratio / 100;
        if ($goodsbrand_ratio > 0) {
            $res = $res * $goodsbrand_ratio / 100;
        }

        return $res;
    }


    /**
     * 获取店铺服务费比例设置
     *
     * @param int $store_id 店铺id
     * @param int $set_id 角色
     * @param int $service_ratio_id 1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
     * @return float
     */
    public function GetSetserverstoreVal($store_id, $set_id, $service_ratio_id)
    {
        $where['set_id'] = $set_id;
        $where['service_ratio_id'] = $service_ratio_id;
        $where['store_id'] = $store_id;

        var_dump('获取店铺服务费比例设置' . '$store_id' . $store_id . '$set_id' . $set_id . '$service_ratio_id' . $service_ratio_id);
        $val = Db::name('setserverstore')->whereEx($where)
            // ->cache($this->db_cache_set)
            ->value('val');
        if (!$val) {
            $where['store_id'] = 1; //平台默认参数
            $val = Db::name('setserverstore')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->value('val');
        }
        return $val;
    }

    //  _____      __  __         ____ __  __ ____  
    // |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
    //   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
    //   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
    //   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/04/08
    //      |_|                                         | TpMeCMS



    /**
     * 创建邀请码
     * @param int $user_id 用户id
     * @return void
     */
    public function EnCode($user_id)
    {
        static $source_string = 'XHQ496318KLYZE5FCDGABNPIJ2RSTUV7MW';
        $num = $user_id;
        $code = '';
        while ($num > 0) {
            $mod = $num % 34;
            $num = ($num - $mod) / 34;
            $code = $source_string[$mod] . $code;
        }
        if (empty($code[3]))
            $code = str_pad($code, 4, '0', STR_PAD_LEFT);
        return $code;
    }


    /**
     * 解邀请码
     * @param string $code 代码
     * @return void
     */
    public function DeCode($code = null)
    {
        static $source_string = 'XHQ496318KLYZE5FCDGABNPIJ2RSTUV7MW';
        if (strrpos($code, '0') !== false)
            $code = substr($code, strrpos($code, '0') + 1);
        $len = strlen($code);
        $code = strrev($code);
        $num = 0;
        for ($i = 0; $i < $len; $i++) {
            $num += strpos($source_string, $code[$i]) * pow(34, $i);
        }
        if ($num < 1)
            return $this->error('错误邀请码');
        return $num;
    }




    /**
     * 获取用户显示模块设置
     *
     * @param int $user_id 用户id
     * @param int $set_id 角色
     * @param int $mod_id 参数
     * @return void
     */
    public function GetUserSetmod($user_id = null, $set_id = null, $mod_id = null)
    {

        $where['user_id'] = $user_id;
        if (!Db::name('setlist')
            ->whereEx($where)
            // 
            // ->cache($this->db_cache_set)

            ->count())
            $where['user_id'] = 1; //平台默认
        if ($set_id)
            $where['set_id'] = $set_id;
        if ($mod_id)
            $where['mod_id'] = $mod_id;

        if ($set_id && $mod_id) {
            $setlist = Db::name('setlist')
                ->whereEx($where)
                // 
                // ->cache($this->db_cache_set)

                ->find();
            return $setlist['switch'];
        } else {
            $setlist = Db::name('setlist')
                ->whereEx($where)
                // 
                // ->cache($this->db_cache_set)

                // ->fieldRaw('store_id,createtime,updatetime,deletetime,setcate_id', true)
                ->select()->getArray();
            return $setlist;
        }
    }


    /**
     * 获取店铺显示模块设置
     *
     * @param int $store_id 店铺id
     * @param int $set_id 角色
     * @param int $mod_id 参数
     * @return void
     */
    public function GetStoreSetmod($store_id = null, $set_id = null, $mod_id = null)
    {

        $where['store_id'] = $store_id;
        if (!Db::name('setlist')->whereEx($where)
            // ->cache($this->db_cache_set)
            ->count())
            $where['store_id'] = 1; //平台默认
        if ($set_id)
            $where['set_id'] = $set_id;
        if ($mod_id)
            $where['mod_id'] = $mod_id;

        if ($set_id && $mod_id) {
            $setlist = Db::name('setlist')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->find();
            return $setlist['switch'];
        } else {
            $setlist = Db::name('setlist')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->fieldRaw('user_id,createtime,updatetime,deletetime,setcate_id', true)->select()->getArray();
            return $setlist;
        }
    }


    /**
     * 更新用户模块显示设置
     *
     * @param int $user_id 用户id
     * @return void
     */
    public function UpdateUserSetlist($user_id = null)
    {
        $mod_list = Db::name('mod')->order('weigh desc')->select()->getArray();

        $set_list = Db::name('set')->order('weigh desc')->where('setcate_id', 1)->select()->getArray();

        foreach ($mod_list as $key_m => $mod) {
            foreach ($set_list as $key_s => $set) {
                unset($data);
                $data['mod_id'] = $mod['id'];
                $data['set_id'] = $set['id'];

                $data['user_id'] = $user_id;

                $res = Db::name('setlist')->whereEx($data)->find();
                if (!$res) {
                    $data['setcate_id'] = $set['setcate_id']; //设置分类
                    $data['name'] = $set['name'] . '|' . $mod['name'];
                    $data['switch'] = 1;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('setlist')->insert($data);
                }
            }
        }
    }


    /**
     * 更新店铺模块显示设置
     *
     * @param int $store_id 店铺id
     * @return void
     */
    public function UpdateStoreSetlist($store_id = null)
    {
        $mod_list = Db::name('mod')->order('weigh desc')->select()->getArray();

        $set_list = Db::name('set')->order('weigh desc')->where('setcate_id', 2)->select()->getArray();

        foreach ($mod_list as $key_m => $mod) {
            foreach ($set_list as $key_s => $set) {
                unset($data);
                $data['mod_id'] = $mod['id'];
                $data['set_id'] = $set['id'];

                $data['store_id'] = $store_id;

                $res = Db::name('setlist')->whereEx($data)->find();
                if (!$res) {
                    $data['setcate_id'] = $set['setcate_id']; //设置分类
                    $data['name'] = $set['name'] . '|' . $mod['name'];
                    $data['switch'] = 1;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('setlist')->insert($data);
                }
            }
        }
    }





    /**
     * 更新店铺服务费设置
     *
     * @param int $store_id 店铺id
     * @return void
     */
    public function UpdateStoreServerRatioSetList($store_id = null)
    {
        $service_ratio_list = Db::name('service_ratio')->order('weigh desc')->select()->getArray();

        $set_list = Db::name('set')->order('weigh desc')->where('setcate_id', 2)->select()->getArray();

        foreach ($service_ratio_list as $key_m => $service_ratio) {
            foreach ($set_list as $key_s => $set) {
                unset($data);
                $data['service_ratio_id'] = $service_ratio['id'];
                $data['set_id'] = $set['id'];

                $data['store_id'] = $store_id;

                $res = Db::name('setserverstore')->whereEx($data)->find();
                if (!$res) {
                    // $data['setcate_id'] = $set['setcate_id']; //设置分类
                    $data['name'] = $set['name'] . '|' . $service_ratio['name'];
                    $data['val'] = 1;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('setserverstore')->insert($data);
                }
            }
        }
    }


    /**
     * 拷贝店铺服务费设置
     *
     * @param int $store_id 店铺id
     * @return void
     */
    public function CopyStoreServerRatioSetList($store_id = null)
    {
        $service_ratio_list = Db::name('service_ratio')->order('weigh desc')
            // ->cache($this->db_cache_set)
            ->select()->getArray();

        $set_list = Db::name('set')->order('weigh desc')->where('setcate_id', 2)
            // ->cache($this->db_cache_set)
            ->select()->getArray();


        foreach ($service_ratio_list as $key_m => $service_ratio) {
            foreach ($set_list as $key_s => $set) {
                unset($data);
                $data['service_ratio_id'] = $service_ratio['id'];
                $data['set_id'] = $set['id'];
                $where = $data;
                $data['store_id'] = $store_id;

                $res = Db::name('setserverstore')->whereEx($data)->find();
                if (!$res) {
                    // $data['setcate_id'] = $set['setcate_id']; //设置分类
                    $data['name'] = $set['name'] . '|' . $service_ratio['name'];
                    $data['val'] = Db::name('setserverstore')->where('store_id', 1)->whereEx($where)->vlaue('val');
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('setserverstore')->insert($data);
                }
            }
        }
    }



    /**
     * 更新买家服务费设置
     *
     * @param int $user_id 买家id
     * @return void
     */
    public function UpdateUserServerRatioSetList($user_id = null)
    {
        $service_ratio_list = Db::name('serviceuser_ratio')->order('weigh desc')
            // ->cache($this->db_cache_set)
            ->select()->getArray();

        $set_list = Db::name('set')->order('weigh desc')->where('setcate_id', 1)
            // ->cache($this->db_cache_set)
            ->select()->getArray();

        foreach ($service_ratio_list as $key_m => $service_ratio) {
            foreach ($set_list as $key_s => $set) {
                unset($data);
                $data['service_ratio_id'] = $service_ratio['id'];
                $data['set_id'] = $set['id'];

                $data['user_id'] = $user_id;

                $res = Db::name('setserveruser')->whereEx($data)->find();
                if (!$res) {
                    // $data['setcate_id'] = $set['setcate_id']; //设置分类
                    $data['name'] = $set['name'] . '|' . $service_ratio['name'];
                    $data['val'] = 1;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('setserveruser')->insert($data);
                }
            }
        }
    }


    /**
     * 拷贝买家服务费设置
     *
     * @param int $user_id 买家id
     * @return void
     */
    public function CopyUserServerRatioSetList($user_id = null)
    {
        $service_ratio_list = Db::name('serviceuser_ratio')->order('weigh desc')
            // ->cache($this->db_cache_set)
            ->select()->getArray();

        $set_list = Db::name('set')->order('weigh desc')->where('setcate_id', 1)
            // ->cache($this->db_cache_set)
            ->select()->getArray();


        foreach ($service_ratio_list as $key_m => $service_ratio) {
            foreach ($set_list as $key_s => $set) {
                unset($data);
                $data['service_ratio_id'] = $service_ratio['id'];
                $data['set_id'] = $set['id'];
                $where = $data;
                $data['user_id'] = $user_id;

                $res = Db::name('setserveruser')->whereEx($data)->find();
                if (!$res) {
                    // $data['setcate_id'] = $set['setcate_id']; //设置分类
                    $data['name'] = $set['name'] . '|' . $service_ratio['name'];
                    $data['val'] = Db::name('setserveruser')->where('user_id', 1)->whereEx($where)
                        // ->cache($this->db_cache_set)
                        ->vlaue('val');
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('setserveruser')->insert($data);
                }
            }
        }
    }


    /**
     * 更新运营设置
     * @param int $run_id 运行id
     * @return void
     */
    public function UpdateRunset($run_id = null)
    {
        $this->UpdateCpmset($run_id);
        // $run_list = Db::name('run')->order('weigh desc')->select()->getArray();
        // $set_list = Db::name('set')->where('setcate_id', '1')->order('weigh desc')->select()->getArray();

        // foreach ($run_list as $key_m => $run) {
        //     foreach ($set_list as $key_s => $set) {
        //         unset($data);
        //         $data['run_id'] = $run['id'];
        //         $data['set_id'] = $set['id'];

        //         $res = Db::name('runset')->whereEx($data)->find();
        //         if (!$res) {
        //             $data['name'] = $set['name'] . '|' . $run['name'];
        //             $data['val'] = 0;
        //             $data['createtime'] = time();
        //             $data['updatetime'] = time();
        //             Db::name('runset')->insert($data);
        //         }
        //     }
        // }

    }




    // /**
    //  * 更新运营中心推广设置
    //  *
    //  * @param int $store_id 运营中心id
    //  * @return void
    //  */
    // public function UpdateStoreSetlist($store_id = null)
    // {
    //     $mod_list = Db::name('mod')->order('weigh desc')->select()->getArray();

    //     $set_list = Db::name('set')->order('weigh desc')->select()->getArray();

    //     foreach ($mod_list as $key_m => $mod) {
    //         foreach ($set_list as $key_s => $set) {
    //             unset($data);
    //             $data['mod_id'] = $mod['id'];
    //             $data['set_id'] = $set['id'];

    //             $data['store_id'] = $store_id;

    //             $res = Db::name('setlist')->whereEx($data)->find();
    //             if (!$res) {
    //                 $data['setcate_id'] = $set['setcate_id']; //设置分类
    //                 $data['name'] = $set['name'] . '|' . $mod['name'];
    //                 $data['switch'] = 1;
    //                 $data['createtime'] = time();
    //                 $data['updatetime'] = time();
    //                 Db::name('setlist')->insert($data);
    //             }
    //         }
    //     }
    // }



    /**
     * 获取用户服务费等参数
     *
     * @param int $user_id 用户id
     * @param int $set_id 角色
     * @param string $field 字段
     * @return float
     */
    public function getUserServerSet($user_id, $set_id, $field)
    {


        // $array =  [
        //     'pay_money_f_shell' => '支付现金贝壳返现%',
        //     'score_max' => '积分最多可用%',
        //     'score_server' => '积分服务费%',
        //     'auction_server' => '拍卖服务费%',
        //     'pay_now_everyday_max' => '立即买单限额/日（元）',
        //     'tixian_server' => '提现服务费%',
        //     'shell_transfer_server' => '贝壳转移服务费%'
        // ];

        $data['user_id'] = $user_id;
        $data['set_id'] = $set_id;
        $res = Db::name('user_serverset_list')->whereEx($data)->find();
        if ($res) {
            return (float)$res[$field];
        } else {
            $data['user_id'] = 1;
            $val = Db::name('user_serverset_list')->whereEx($data)->value($field);
            return (float)$val;
        }
    }


    /**
     * 获取Com1set用户晋级设置
     *
     * @param int $set_id 角色
     * @param int $com1_id 参数
     * @return void
     */
    public function GetCom1set($set_id = null, $com1_id = null)
    {
        $where = null;
        if ($set_id)
            $where['set_id'] = $set_id;
        if ($com1_id)
            $where['com1_id'] = $com1_id;

        if ($set_id && $com1_id) {
            $com1set = Db::name('com1set')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->find();
            return $com1set['val'];
            // return $this->success($com1set['name'], $com1set['val']);
        } else {
            $com1set = Db::name('com1set')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->select()->getArray();
            return $com1set;
            // return $this->success('list', $com1set);
        }
    }


    /**
     * 获取cpmset推广设置
     *
     * @param int $run_id 运营id
     * @param int $set_id 角色
     * @param int $cpm_id 参数
     * @return void
     */
    public function GetCpmset($run_id = 1, $set_id = null, $cpm_id = null)
    {
        $where['run_id'] = $run_id;
        if ($set_id)
            $where['set_id'] = $set_id;
        if ($cpm_id)
            $where['cpm_id'] = $cpm_id;

        if ($set_id && $cpm_id) {
            $cpmset = Db::name('cpmset')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->find();
            return $cpmset['val'];
            // return $this->success($cpmset['name'], $cpmset['val']);
        } else {
            $cpmset = Db::name('cpmset')->whereEx($where)
                // ->cache($this->db_cache_set)
                ->select()->getArray();
            return $cpmset;
            // return $this->success('list', $cpmset);
        }
    }



    /**
     * 更新用户推广设置
     * @return void
     */
    public function UpdateCpmset($run_id = null)
    {
        $cpm_list = Db::name('cpm')->order('weigh desc')
            // ->cache($this->db_cache_set)
            ->select()->getArray();
        $set_list = Db::name('set')->where('setcate_id', '1')->order('weigh desc')
            // ->cache($this->db_cache_set)
            ->select()->getArray();


        foreach ($cpm_list as $key_m => $cpm) {
            foreach ($set_list as $key_s => $set) {
                unset($data);
                $data['cpm_id'] = $cpm['id'];
                $data['set_id'] = $set['id'];
                $data['run_id'] = $run_id;

                $res = Db::name('cpmset')->whereEx($data)->find();
                if (!$res) {
                    $data['name'] = $set['name'] . '|' . $cpm['name'];
                    $data['val'] = 0;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('cpmset')->insert($data);
                }
            }
        }
        // return $this->success('更新成功');
    }

    /**
     * 验证文字
     *
     * @param string|array $str 文字
     * @return void
     */
    public function VerifyStr($str = null)
    {
        // //小程序违禁词
        // $app = $this->get_app();
        // $result = $app->content_security->checkText($str);
        // if($result['errcode']!='0'){
        //    return $this->error('含有违禁词');
        // }
        // //小程序违禁词

        if (config('own_ban_switch') == '1') {

            // \Imi\Cache\CacheManager::set('redis', 'ban_word_list', false, 6);
            $list = \Imi\Cache\CacheManager::get('redis', 'ban_word_list');
            // var_dump('che',$list);
            if (!$list) {
                $list = Db::name('ban_word')
                    ->whereIsNotNull('name')
                    // ->cache($this->db_cache_set)
                    ->select()->getArray();

                //分隔缓存
                // foreach ($list as $key => $val) {
                //     $new = explode('、', $val['name']);

                //     foreach ($new as $name) {
                //         if (strlen($name) > 0) {
                //             $res = Db::name('ban_word')->where('name', '=', $name)->find();
                //             if (!$res) {
                //                 Db::name('ban_word')->insert(['name' => $name]);
                //             }
                //         }
                //     }
                // }

                // $list = Db::name('ban_word')
                //     ->whereIsNotNull('name')
                //     // ->cache($this->db_cache_set)
                //     ->select()->getArray();
                // var_dump('缓存', $list);
                \Imi\Cache\CacheManager::set('redis', 'ban_word_list', $list, 60);
            }



            if ($list) {
                //     foreach ($list as $key => $ban) {
                //         if(strpos($str,$ban['name']) !== false){ 
                //            return $this->error('违禁词：'.$ban['name']);
                //         }
                //     }
                if (is_array($str)) {
                    foreach ($str as $key => $name) {
                        $this->SelfVerifyStr($name, $list);
                    }
                } else {
                    $this->SelfVerifyStr($str, $list);
                }
            }
        }
        return xss_clean($str);
    }

    /**
     * XSS清理并验证违禁词
     * 
     * @param string $str 
     * @return string
     */
    public function Xss($str)
    {
        $this->VerifyStr($str);
        return xss_clean($str);
    }

    /**
     * 更新用户邀请码
     *
     * @param int $user_id 用户id
     * @return void
     */
    public function UpdateUserInviteCode($user_id)
    {



        // $qr = new \addons\qrcode\controller\Index;
        $code = $this->EnCode($user_id);

        $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data(json_encode(['user_invite_code' => $code]))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(10)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            // ->logoPath(__DIR__.'/assets/symfony.png')

            // ->labelText('用户ID:'.$user_id)
            // ->labelFont(new NotoSans(20))
            // ->labelAlignment(new LabelAlignmentCenter())
            ->validateResult(false)
            ->build();
        $file_name = md5(json_encode(['user_invite_code' => $code])) . '.png';
        $pathArr = $this->GetQrPath(1);
        $file_path = $pathArr['file_path'] . $file_name;
        $path = $pathArr['path'] . $file_name;
        $result->saveToFile($file_path);


        // var_dump('user_id',$user_id);


        // $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/'.$folder.'/';
        // $file_path = '/uploads/qrcode/'.$folder.'/';
        // if (!is_dir($qrcodePath)) {
        //     @mkdir($qrcodePath);
        // }
        // if (is_really_writable($qrcodePath)) {
        //     $name = md5(implode('', $params)) . '.' . $config['format'];
        //     $filePath = $qrcodePath . $name;
        //     $qrCode->writeFile($filePath);
        // } else {
        //    return $this->error('没有写入权限' . $file_path);
        // }
        // return  $file_path . $name;

        // $qr = $qr->get_qr(json_encode(['user_invite_code' => $code]));
        Db::name('user')->where('id', '=', $user_id)->update(['qr' => $path, 'invite_code' => $code]);
    }



    /**
     * 更新店铺二维码
     *
     * @param int $store_id 店铺id
     * @return void
     */
    public function UpdateStoreQrCode($store_id)
    {



        // $qr = new \addons\qrcode\controller\Index;
        $code = $this->EnCode($store_id);

        $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data(json_encode(['store_id' => $code]))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(10)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            // ->logoPath(__DIR__.'/assets/symfony.png')

            // ->labelText('用户ID:'.$store_id)
            // ->labelFont(new NotoSans(20))
            // ->labelAlignment(new LabelAlignmentCenter())
            ->validateResult(false)
            ->build();
        $file_name = md5(json_encode(['store_id' => $code])) . '.png';
        $pathArr = $this->GetQrPath(2);
        $file_path = $pathArr['file_path'] . $file_name;
        $path = $pathArr['path'] . $file_name;
        $result->saveToFile($file_path);


        // var_dump('store_id',$store_id);


        // $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/'.$folder.'/';
        // $file_path = '/uploads/qrcode/'.$folder.'/';
        // if (!is_dir($qrcodePath)) {
        //     @mkdir($qrcodePath);
        // }
        // if (is_really_writable($qrcodePath)) {
        //     $name = md5(implode('', $params)) . '.' . $config['format'];
        //     $filePath = $qrcodePath . $name;
        //     $qrCode->writeFile($filePath);
        // } else {
        //    return $this->error('没有写入权限' . $file_path);
        // }
        // return  $file_path . $name;

        // $qr = $qr->get_qr(json_encode(['user_invite_code' => $code]));
        Db::name('store')->where('id', '=', $store_id)->update(['qr' => $path, 'invite_code' => $code]);
        return $path;
    }



    /**
     * 获取二维码路径
     *
     * @param string $type 类型1=个人,2=店铺
     * @return void
     */
    public function GetQrPath($type = 1)
    {
        switch ($type) {
            case '1':
                $data['file_path'] = dirname(dirname(dirname(__DIR__))) . '/public/uploads/qrcode/user/';
                $data['path'] = '/uploads/qrcode/user/';
                break;
            case '2':
                $data['file_path'] = dirname(dirname(dirname(__DIR__))) . '/public/uploads/qrcode/store/';
                $data['path'] = '/uploads/qrcode/store/';
                break;
            default:
                break;
        }

        return $data;
    }

    /**
     * 获取商品分类下的子分类
     *
     * @param string|array $goodscate_ids 商品分类
     * @return array
     */
    public function GetGoodscateSub($goodscate_ids)
    {
        if ($goodscate_ids) {
            $this->model = Goodscate::dbQuery();
            if (is_string($goodscate_ids))
                $goodscate_ids = explode(',', $goodscate_ids);
            // $list = $this->model->with('children.children.children')->where('id', 'in',$goodscate_ids)->column('id');
            $list = $this->model->whereIn('pid',  $goodscate_ids)->select()->getArray();
            $new = [];
            foreach ($list as $key => $val) {
                if ($val['level'] < 2) {
                    $res = $this->GetGoodscateSub($val['id']);
                    if ($res)
                        $new = array_merge($new, $res);
                } else {
                    $new[] = $val['id'];
                }
            }

            $new = array_merge($new, $goodscate_ids);
            return $new;
        }
    }

    /**
     * 判断主分类
     * @param string $ltd_status 公司类型
     * @param string $goodscate_ids 商品分类ids
     * @return void
     */
    public function JudgeGoodscateIds($ltd_status, $goodscate_ids)
    {
        switch ($ltd_status) {
            case '1':
                //个人只能一个主分类
                if (sizeof(explode(',', $goodscate_ids)) > 1) {
                    return $this->error('个人店铺只能一个分类', $goodscate_ids, CODE_个人店铺主营分类限制);
                }
                break;
            case '2':
                //企业只能3个主分类
                if (sizeof(explode(',', $goodscate_ids)) > 3) {
                    return $this->error('企业店铺只能三个分类', $goodscate_ids, CODE_企业店铺主营分类限制);
                }
                break;
            default:
                return $this->error('主营分类参数错误', $ltd_status, CODE_主营分类参数错误);
                break;
        }
    }

    /**
     * 实名验证
     * 
     * @param int $user_id 用户id
     * @return void
     */
    public function VerifyRealName($user_id = null)
    {
        if (!$user_id) {
            if (!$this->auth->isLogin()) {
                return $this->error('请登陆');
            }
            $user = Db::name('user')->where('id', '=', $this->auth->user()->id)->find();
            // $user_id = $this->auth->user()->id;
            // if ($this->auth->user()->real_status == '1')
            if ($user['real_status'] == '1')
                return true;
            return $this->error('请先实名认证', null, CODE_请先实名认证);
        } else {
            $real_status = Db::name('user')->where('id', '=', $user_id)->value('real_status');
            if ($real_status == '1')
                return true;
            return $this->error('请先实名认证', null, CODE_请先实名认证);
        }
    }

    /**
     * 验证实名接口
     *
     * @param array $data 
     * @return void
     */
    public function VerifyRealNameApi($data)
    {

        $idcard = $data['sfz']; //身份证号
        $mobile =  $data['mobile']; //电话
        $name =  $data['name']; //姓名

        $host = "https://slysjsys.market.alicloudapi.com";
        $path = "/check";
        $method = "GET";    //204118979
        $appcode = config('real_name_key');
        $headers = array();
        array_push($headers, "Content-type:application/json;");
        array_push($headers, "Accept:application/json");
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "idcard=" . $idcard . "&mobile=" . $mobile . "&name=" . urlencode($name);
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        $res = curl_exec($curl);
        curl_close($curl);

        $res = explode('{"msg"', $res);
        $json =  '{"msg"' . $res[1];

        // file_put_contents('sfz.txt', $idcard . '_' . $mobile . '_' . $name . PHP_EOL . $json, FILE_APPEND);
        $res = json_decode($json, true);
        if ($res['success'] && $res['code'] == 200) {
            return true;
        } else {
            // file_put_contents('sfz_error.txt',$idcard.':'.PHP_EOL.$json.PHP_EOL,FILE_APPEND);
            // return false;
            return $this->error($res['msg']);
        }
    }

    /**
     * 自己系统验证
     *
     * @param string $str 待验证字符串
     * @param array $list 违禁词组
     * @return void
     */
    protected function SelfVerifyStr($str = null, $list = null)
    {
        foreach ($list as $key => $ban) {
            if (isset($ban['name']) && $ban['name'] && $str)
                if (strpos($str, $ban['name']) !== false) {
                    return $this->error('违禁词：' . $ban['name'], null, CODE_含有违禁词);
                }
        }
    }

    /**
     * 验证身份证id
     *
     * @param string $card 身份证号码
     * @return void
     */
    protected function check_sfz_card($card)
    {
        $city = [11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江 ", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北 ", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏 ", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外 "];
        $tip = "";
        $match = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/";
        $pass = true;
        if (!$card || !preg_match($match, $card)) {
            //身份证格式错误
            $pass = false;
        } else if (!$city[substr($card, 0, 2)]) {
            //地址错误
            $pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (strlen($card) == 18) {
                $card = str_split($card);
                //∑(ai×Wi)(mod 11)
                //加权因子
                $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                $parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                $sum = 0;
                $ai = 0;
                $wi = 0;
                for ($i = 0; $i < 17; $i++) {
                    $ai = $card[$i];
                    $wi = $factor[$i];
                    $sum += $ai * $wi;
                }
                $last = $parity[$sum % 11];
                if ($parity[$sum % 11] != $card[17]) {
                    //                        $tip = "校验位错误";
                    $pass = false;
                }
            } else {
                $pass = false;
            }
        }
        if (!$pass) return false;/* 身份证格式错误*/
        return true;/* 身份证格式正确*/
    }



    /**
     * 获取区域id
     *
     * @param int $id 
     * @return void
     */
    protected function GetAreaAllData($id)
    {
        $area = $this->GetAreaDataCom($id);
        if (!$area) {
            return $this->error('没有该地区', $id);
        }
        switch ($area['level']) {
            case '1':
                $data['area_id'] = $area['id'];


                $data['city_id'] = null;
                $data['province_id'] = $area['id'];
                break;
            case '2':
                $data['area_id'] = $area['id'];

                $data['city_id'] = $area['id'];
                $data['province_id'] = $area['pid'];
                break;
            case '3':
                $data['area_id'] = $area['id'];
                $data['district_id'] = $area['id'];
                $data['city_id'] = $area['pid'];
                $area_p = $this->GetAreaDataCom($area['pid']);
                $data['province_id'] = $area_p['pid'];
                break;
            case '4':
                $data['area_id'] = $area['id'];
                $data['town_id'] = $area['id'];
                $data['district_id'] = $area['pid'];

                $district = $this->GetAreaDataCom($area['pid']);
                $data['city_id'] = $district['pid'];
                $city = $this->GetAreaDataCom($district['pid']);
                $data['province_id'] = $city['pid'];
                break;
            default:
                var_dump($area);
                return $this->error('地区数据错误');
                break;
        }
        return $data;
    }

    /**
     * 获取区域名
     *
     * @param int $id 
     * @return void
     */
    protected function GetAreaName($id)
    {
        if ($id) {
            $area = $this->GetAreaDataCom($id);
            // $data = trim($area['mergename'], '中国,');
            $data = $area['mergename'];
            return $data;
        }
    }

    /**
     * 获取地区信息
     * 
     * @param int $id
     * @return void
     */
    protected function GetAreaDataCom($id)
    {
        return Db::name('area')->where('id', '=', $id)->find();
    }

    /**
     * 获取用户设置是否是临时身份
     * @param int $user_id 用户id
     * @return void
     */
    public function GetUserSetIsTemp($user_id)
    {
        return Db::name('user_set_temp')->where('user_id', $user_id)
            // ->cache($this->db_cache_set)
            ->find();
        // 正式升级的创客或合伙人 
        // 1、收益转余额无解锁，可随时转余额，临时的只能解锁一次
        // 2、正式的可担保，临时的不可担保
        // 其他都一样
    }


    /**
     * 注册用户修改上级
     * @param int $user_id 被邀请用户
     * @param int $pid 上级id
     * @return void
     */
    public function RegUpdateUserPid($user_id, $pid)
    {
        $this->UpdateUserPid($user_id, $pid, '注册更新上级');

        //加积分

        $pid_user = Db::name('user')->where('id', '=', $pid)->find();
        Db::name('user')->where('id', '=', $user_id)->update(['run_id' => $pid_user['run_id']]);
        $data['set_id'] = $pid_user['set_id']; //Db::name('user')->where('id', '=', $pid)->value('set_id');
        $data['user_id'] = $user_id;
        $data['uid'] = $pid;
        $data['run_id'] = $pid_user['run_id'];
        $data['createtime'] = time();

        // $data['score'] = $this->GetCpmsetScore($pid_user['run_id'],$pid_user['set_id'],1);//获取成功邀请积分 1直推

        $score = $this->GetShareRegScore();
        $data['score'] = $score;

        $id = Db::name('pid')->insert($data)->getLastInsertId();
        $this->IncUserScore($pid, $score, '邀请用户注册', 2, $id);

        // //判断是否有间接上级 然后赠送积分 
        // if($pid_user['pid']>0){ //
        //     $ppid_user = Db::name('user')->where('id', '=', $pid_user['pid'])->find();
        //     $data['score'] = $this->GetCpmsetScore($ppid_user['run_id'],$ppid_user['set_id'],2);//获取成功邀请积分 2间推
        // }

        //判断上级邀请人数是否达到升级
        $this->UserSetIsRiseTeamNum($pid);
    }

    /**
     * 判断上级邀请人数是否达到升级
     *
     * @param int $pid
     * @return void
     */
    protected function UserSetIsRiseTeamNum($pid)
    {
        $user = Db::name('user')->where('id', '=', $pid)->find();

        $team_num = $this->GetCom1set($user['set_id'], 3); //1=拼中/拍中数,2=邀请成功积分,3=团队数量
        $where['pid'] = $pid;
        $where['set_id'] = ['>=', $user['set_id']];

        //现在已有团队数
        $now_team_num = Db::name('user')->whereEx($where)->count();
        $user_ids = Db::name('user')->whereEx($where)->column('id');

        //判断团队数量是否达到
        if ($now_team_num >= $team_num) {
            //用户升级
            $this->UpgradeUserSet($pid, 3, '团队设定' . $team_num . ',当前团队' . $now_team_num . '用户IDS' . implode(',', $user_ids)); //状态:1=拍OR拼晋级,2=积分晋级,3=团队晋级,5=连续签到晋级
            // if()
            $pid_user = Db::name('user')->where('id', '=', $user['pid'])->find();
            //如果上级是运营中就不在循环给上级
            if ($pid_user && ($pid_user['set_id'] == 6 || $pid_user['set_id' == 5])) { //售后站和运营中心

            } else {
                if ($user['pid'] > 0 && $user['pid'] != 1)
                    $this->UserSetIsRiseTeamNum($user['pid']);
            }
        }
    }


    /**
     * 判断上级邀请人数是否达到升级2
     *
     * @param int $pid
     * @return void
     */
    public function UserSetIsRiseTeamNum2($id)
    {
        $user = Db::name('user')->where('id', '=', $id)->find();

        $team_num = $this->GetCom1set($user['set_id'], 3); //1=拼中/拍中数,2=邀请成功积分,3=团队数量
        $where['pid'] = $id;
        $where['set_id'] = ['>=', $user['set_id']];

        //现在已有团队数
        $now_team_num = Db::name('user')->whereEx($where)->count();
        $user_ids = Db::name('user')->whereEx($where)->column('id');
        $low_num = Db::name('user')->where('pid', '=', $id)->count();
        $不判断下级人数升级 = false;
        if ($user['pid'] > 0) {
            if ($low_num >= 2) {
                $不判断下级人数升级 = true;
            } else {
                return ['code' => -1, 'msg' => '下级没有达到2个人'];
            }
        } else {
            $不判断下级人数升级 = true;
        }

        //判断团队数量是否达到
        if ($now_team_num >= $team_num && $不判断下级人数升级) {
            //用户升级
            var_dump($user_ids, implode(',', $user_ids));
            $this->UpgradeUserSet($id, 3, '点击升级,团队设定' . $team_num . ',当前团队' . $now_team_num . '用户IDS' . implode(',', $user_ids), true); //状态:1=拍OR拼晋级,2=积分晋级,3=团队晋级,5=连续签到晋级

            $pid_user = Db::name('user')->where('id', '=', $user['pid'])->find();

            //如果上级是运营中就不在循环给上级
            if ($pid_user && ($pid_user['set_id'] == 6 || $pid_user['set_id' == 5])) { //售后站和运营中心
                return ['code' => -1, 'msg' => '上级是售后站或运营中心'];
            } else {
                if ($user['pid'] > 0 && $user['pid'] != 1)
                    $this->UserSetIsRiseTeamNum($user['pid']);
            }


            // if ($user['pid'] > 0 && $user['pid'] != 1)
            //     $this->UserSetIsRiseTeamNum($user['pid']);
            return ['code' => 1, 'msg' => '团队数已达到'];
        } else {
            return ['code' => -1, 'msg' => $user['set_id'] . '团队数未达到' . $team_num . '现在团队数' . $now_team_num];
        }
    }

    /**
     * 用户升级
     *
     * @param int $user_id 用户id
     * @param string $status 状态:1=拍OR拼晋级,2=积分晋级,3=团队晋级,5=连续签到晋级
     * @param string $ps 备注
     * @return void
     */
    protected function UpgradeUserSet($user_id, $status, $ps = null, $click = false)
    {
        $user = Db::name('user')->where('id', '=', $user_id)->find();

        $data['user_id'] = $user_id;
        $data['before'] = $user['set_id'];

        $data['status'] = $status;
        $data['createtime'] = time();
        $data['memo'] = $ps;
        $data['after'] = $user['set_id'];



        switch ($user['set_id']) {
                //1换客 2拼客 3拍客 4创客 5合伙人
            case '1': //
                if ($user['pid'] > 0) {
                    $this->UserSetIsRiseTeamNum($user['pid']); //判断上级邀请人数是否达到升级
                }
                $data['after'] = $user['set_id'] + 1;
                break;

            case '2': //
                if ($user['pid'] > 0) {
                    $this->UserSetIsRiseTeamNum($user['pid']); //判断上级邀请人数是否达到升级
                }
                $data['after'] = $user['set_id'] + 1;
                break;

            case '3': //3拍客
                if ($click) { //需要用户点击升级
                    //如果上级是创客就绑定到运营中心
                    if ($user['pid'] > 0) {
                        $p_user = Db::name('user')->where('id', '=', $user['pid'])->find();
                        if ($p_user['set_id'] <= 4) {
                            //留2个下级给原来上级
                            var_dump('4留2个下级给原来上级');
                            $this->UpdateLowUserPid($user_id, $user['pid'], "原拍客id:{$user_id}晋级创客,上级id{$user['pid']},角色拍客,下级用户迁移");
                            //变更上级到运营中心
                            $this->UpdateUserPidRun($user_id, $p_user['run_id'], "拍客晋级,上级id{$user['pid']},角色创客,到运营中心");
                        } else {
                            $this->UserSetIsRiseTeamNum($user['pid']); //判断上级邀请人数是否达到升级
                        }
                    }
                    $data['after'] = $user['set_id'] + 1;
                }

                break;

            case '4': //4创客
                if ($click) { //需要用户点击升级
                    //如果上级是5合伙人就绑定到运营中心 
                    if ($user['pid'] > 0) {
                        $p_user = Db::name('user')->where('id', '=', $user['pid'])->find();
                        if ($p_user['set_id'] <= 5) {
                            //留2个下级给原来上级
                            var_dump('5留2个下级给原来上级');
                            $this->UpdateLowUserPid($user_id, $user['pid'], "原创客id:{$user_id}晋级合伙人,上级id{$user['pid']},角色创客,下级用户迁移");
                            //变更上级到运营中心
                            $this->UpdateUserPidRun($user_id, $p_user['run_id'], "创客晋级,上级id{$user['pid']},角色合伙人,到运营中心");
                        } else {
                            $this->UserSetIsRiseTeamNum($user['pid']); //判断上级邀请人数是否达到升级
                        }
                    }
                    $data['after'] = $user['set_id'] + 1;
                }

                break;

            case '5': //5合伙人


                break;

            default:

                break;
        }

        Db::name('user_upgrade_set_log')->insert($data);

        $update['set_id'] = $data['after'];
        Db::name('user')->where('id', '=', $user_id)->update($update);
    }

    /**
     * 修改下级2个给原来上级
     * @param int $user_id 用户id
     * @param int $pid 原上级
     * @param string $ps 备注
     * @return void
     */
    public function UpdateLowUserPid($user_id, $pid = null, $ps = null)
    {
        $user_arr = Db::name('user')->where('pid', '=', $user_id)->column('id');
        $all_user_num = sizeof($user_arr);


        $i = 0;
        if ($all_user_num <= 2) {
            //下级人数不足

            foreach ($user_arr as $key => $id) {
                $i++;
                $this->UpdateUserPid($id, $pid, $ps . "第{$i}个");

                if ($i >= 2)
                    break;
            }
        } else {

            //排除店铺人数,如果店铺人数排出后不足照样给上级
            $store_user_arr = Db::name('store')->where('user_id', 'in',  $user_arr)->column('user_id');
            if ($store_user_arr) {
                //算差集
                $diff_user_arr = array_diff($user_arr, $store_user_arr);
                if (sizeof($diff_user_arr) >= 2) {
                    $user_arr = $diff_user_arr;
                }
            }

            foreach ($user_arr as $key => $id) {
                $i++;
                $this->UpdateUserPid($id, $pid, $ps . "第{$i}个");

                if ($i >= 2)
                    break;
            }
        }
    }



    public function 获取增长比例($当前, $以前)
    {
        $ratio = 0;
        if ($当前 > 0 && $以前 > 0) {
            return round($当前 / $以前 * 100);
        } else {
            if ($当前 > 0)
                $ratio = 100;
            if ($以前 > 0)
                $ratio = 0;
        }
        return $ratio;
    }



    /**
     * 获取运营中心固定用户占比
     *
     * @param int $run_id 运营中心id
     * @return 
     * @throws
     **/
    public function 获取运营中心固定用户占比($run_id)
    {
        return Db::name('run_bonus_user_sys')->where('run_id', '=', $run_id)->sum('ratio') ?? 0;
    }


    /**
     * 获取运营中心下的用户数组
     *
     * @param int $run_id 运营中心id
     * @return 
     * @throws
     **/
    public function 获取运营中心下的用户数组($run_id)
    {
        return Db::name('user')->where('run_id', '=', $run_id)->column('id');
    }

    public function 运营中心下用户消费额(?int $run_id, ?int $开始时间 = null, ?int $结束时间 = null)
    {
        $user_ids = $this->获取运营中心下的用户数组($run_id);
        $money = Db::name('order_item')
            ->where('user_id', 'in', $user_ids)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('pay_fee');
        $score = Db::name('order_item')
            ->where('user_id', 'in', $user_ids)
            ->where('status', '=', '2')
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('score_fee');
        $shell = Db::name('order_item')
            ->where('user_id', 'in', $user_ids)
            ->where('status', '=', '2')
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('shell_fee');

        $运费 = Db::name('order')
            ->where('user_id', 'in', $user_ids)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('dispatch_amount');

        $count = $money + $score + $shell + $运费;


        return $count;
    }


    /**
     * 获取运营中心下的店铺
     *
     * @param int $run_id 运营中心id
     * @return 
     * @throws
     **/
    public function 获取运营中心下的店铺数组($run_id)
    {
        return Db::name('store')->where('run_id', '=', $run_id)->column('id');
    }



    public function 运营中心下店铺销售额(?int $run_id, ?int $开始时间 = null, ?int $结束时间 = null)
    {
        $store_ids = $this->获取运营中心下的店铺数组($run_id);
        $money = Db::name('order_item')
            ->where('store_id', 'in', $store_ids)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('pay_fee');
        $score = Db::name('order_item')
            ->where('store_id', 'in', $store_ids)
            ->where('status', '=', '2')
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('score_fee');
        $shell = Db::name('order_item')
            ->where('store_id', 'in', $store_ids)
            ->where('status', '=', '2')
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('shell_fee');

        $give_shell = Db::name('order_item')
            ->where('store_id', 'in', $store_ids)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('coupons_sys_give_shell');

        $count = $money + $score + $shell + $give_shell;


        return $count;
    }

    public function 店铺销售额(?int $store_id, ?int $开始时间 = null, ?int $结束时间 = null)
    {
        $money = Db::name('order_item')
            ->where('store_id', '=', $store_id)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('pay_fee');
        $score = Db::name('order_item')
            ->where('store_id', '=', $store_id)
            ->where('status', '=', '2')
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('score_fee');
        $shell = Db::name('order_item')
            ->where('store_id', '=', $store_id)
            ->where('status', '=', '2')
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('shell_fee');

        $give_shell = Db::name('order_item')
            ->where('store_id', '=', $store_id)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('coupons_sys_give_shell');

        $count = $money + $score + $shell + $give_shell;


        return $count;
    }


    public function 店铺销售money(?int $store_id, ?int $开始时间 = null, ?int $结束时间 = null)
    {
        $money = Db::name('order_item')
            ->where('store_id', '=', $store_id)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('pay_fee');
        return $money;
    }

    public function 店铺销售shell(?int $store_id, ?int $开始时间 = null, ?int $结束时间 = null)
    {
        $shell = Db::name('order_item')
            ->where('store_id', '=', $store_id)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('shell_fee');
        return $shell;
    }

    public function 店铺销售score(?int $store_id, ?int $开始时间 = null, ?int $结束时间 = null)
    {
        $score = Db::name('order_item')
            ->where('store_id', '=', $store_id)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('score_fee');
        return $score;
    }

    public function 店铺销售优惠券返贝壳(?int $store_id, ?int $开始时间 = null, ?int $结束时间 = null)
    {
        $shell = Db::name('order_item')
            ->where('store_id', '=', $store_id)
            ->where('status', '=', '2') ////订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $开始时间)
            ->where('createtime', '<', $结束时间)
            ->sum('coupons_sys_give_shell');
        return $shell;
    }

    /**
     * 获取用户id
     * @param int $run_id 运营中心id
     * @return void
     */
    public function GetUserIdByRunId($run_id)
    {
        return Db::name('run')->where('id', '=', $run_id)
            // ->cache($this->db_cache_set)
            ->value('user_id');
    }


    /**
     * 获取邀请用户注册积分
     * 
     * @return float
     */
    public function GetShareRegScore()
    {
        return Db::name('taskscore_set')->where('id', '=', 3)
            // ->cache($this->db_cache_set)
            ->value('score');
    }

    /**
     * 获取每日签到积分
     * @return float
     */
    public function GetEveryDaySignScore()
    {
        return Db::name('taskscore_set')->where('id', '=', 1)
            // ->cache($this->db_cache_set)
            ->value('score');
    }

    /**
     * 获取推广积分值
     * @param int $run_id 运营中心id
     * @param int $set_id 用户角色id
     * @param int $cpm_id 推广id
     * @return float
     */
    public function GetCpmsetScore($run_id, $set_id, $cpm_id)
    {
        $r = $this->GetCpmset($run_id, $set_id, $cpm_id); //比例
        $r = $this->ChangeRatio($r);
        $v = $this->GetCpmset($run_id, 6, $cpm_id); //获取邀请积分
        if ($r * $v >= 0)

            return $r * $v;
        return 0;
    }


    /**
     * 比率转换
     *
     * @param int $ratio
     * @return float
     */
    public function ChangeRatio($ratio)
    {
        if ($ratio < 1 && $ratio > 0) {
            return $ratio;
        } elseif ($ratio >= 1) {
            return ($ratio / 100);
        } else {
            return 0;
        }
    }

    /** 
     * 更新用户上级到运营中心
     *
     * @param int $user_id 被邀请用户
     * @param int $pid 上级id
     * @param string $ps 备注
     * @return void
     */
    public function UpdateUserPidRun($user_id, $run_id, $ps = null)
    {
        $run = Db::name('run')->where('id', '=', $run_id)->find();
        $pid = $run['user_id'];
        $this->UpdateUserPid($user_id, $pid, $ps);
    }


    /**
     * 更新用户上级
     *
     * @param int $user_id 被邀请用户
     * @param int $pid 上级id
     * @param string $ps 备注
     * @return void
     */
    protected function UpdateUserPid($user_id, $pid, $ps = null)
    {
        $data['pid'] = $pid;
        //如果第一次就吧原上级复制进去
        $user = Db::name('user')->where('id', '=', $user_id)->find();
        // $old_pid = Db::name('user')->where('id', '=', $user_id)->value('old_pid');
        $old_pid = $user['old_pid'];

        if ($old_pid < 1) {
            $data['old_pid'] = $pid;
        } else {
            $data['before_pid'] = $old_pid;
        }
        $insert['user_id'] = $user_id;
        $insert['pid'] = $pid;
        $insert['old_pid'] = $user['pid'];
        $insert['ps'] = $ps;
        $insert['createtime'] = time();
        Db::name('user_pid_log')->insert($insert);


        Db::name('user')->where('id', '=', $user_id)->update($data);
    }



    /**
     * 获取用户信息头像昵称
     *
     * @param int $id 用户id
     * @return void
     */
    protected function GetUserData1($id)
    {
        return Db::name('user')->where('id', '=', $id)->fieldRaw('nickname,avatar')
            // ->cache($this->db_cache_set)
            ->find();
    }

    /**
     * 获取用户信息头像昵称id
     * 
     *
     * @param int $id 用户id
     * @return void
     */
    protected function GetUserData2($id)
    {
        return Db::name('user')->where('id', '=', $id)->fieldRaw('nickname,avatar,id')
            // ->cache($this->db_cache_set)
            ->find();
    }

    /**
     * 公共支付
     *
     * @param int $typestatus_id 订单类型
     * @param int $public_id 公共id
     * @param int $money 金额
     * @param int $uid 用户
     * @param int $paystatus_id 支付类型
     * @param int $ps 备注
     * @return void
     */
    protected function ComPayOrder($typestatus_id, $public_id, $money, $uid, $paystatus_id, $ps = null)
    {

        $user = Db::name('user')->where('id', '=', $uid)->find();
        if ($money > $user['money']) {
            return $this->error('余额不足', $public_id);
        }
        if (!$ps) {
            $paystatus = Db::name('paystatus')->where('id', '=', $paystatus_id)->find();
            if ($paystatus) {
                $ps = strlen($paystatus['ps']) > 1 ? $paystatus['ps'] : $paystatus['name'];
            }
        }
        // switch ($typestatus_id) {
        //     case '1':

        //         break;
        //     case '9':
        //         $ps = '支付顺风车信息费，ID:'.$public_id;
        //         break;
        //     default:
        //         $ps = '支付费用类型'.$typestatus_id.'ID:'.$public_id;
        //         break;
        // }
        $data['typestatus_id'] = $typestatus_id;
        $data['public_id'] = $public_id;
        $data['money'] = $money;
        $data['uid'] = $uid;
        $data['paystatus_id'] = $paystatus_id;
        $res = Db::name('com_order')->whereEx($data)->where('pay_status', '1')->find();
        if ($res)
            return $res;


        Db::startTrans();
        try {


            $data['ps'] = $ps;
            $id = Db::name('com_order')->insert($data)->getLastInsertId();

            //减去金额
            $this->DecUserMoney($uid, $money, $ps, $paystatus_id, $id);

            //修改支付状态
            $data2['pay_time'] = time();
            $data2['pay_status'] = '1';
            Db::name('com_order')->where('id', '=', $id)->update($data2);

            //确认提交
            Db::commit();
        } catch (\Throwable $th) {
            //回滚
            Db::rollback();
            return $this->error('支付失败', $th->getMessage());
        }
    }

    /**
     * 添加收藏
     *
     * @param int $typestatus_id 类型id用户1 店铺2 商品3  
     * @param int $public_id 公共id
     * @param int $user_id 用户id
     * @return void
     */
    protected function AddShoucang($typestatus_id, $public_id, $user_id)
    {
        $data['typestatus_id'] = $typestatus_id;
        $data['public_id'] = $public_id;
        $data['user_id'] = $user_id;
        $res = Db::name('likes')->whereEx($data)->find();
        if ($res) {
            return $this->error('您已收藏');
        }
        $data['time'] = time();
        $data['id'] = Db::name('likes')->insert($data)->getLastInsertId();
        return $data;
    }


    /**
     * 是否收藏商品
     *
     * @param int $goods_id 商品id
     * @param int $goods_sku_price_id 价格id
     * @param int $user_id 用户id
     * @return void
     * 
     */
    public function IsLikesGoods($goods_id, $goods_sku_price_id = null, $user_id)
    {
        $where['goods_id'] = $goods_id;
        if ($goods_sku_price_id)
            $where['goods_sku_price_id'] = $goods_sku_price_id;
        $where['user_id'] = $user_id;
        $res = Db::name('likesgoods')->whereEx($where)->find();
        if ($res)
            return true;
        return false;
    }


    /**
     * 是否收藏
     *
     * @param int $typestatus_id 类型id
     * @param int $public_id 公共id
     * @param int $user_id 用户id
     * @return void
     */
    protected function IsShoucang($typestatus_id, $public_id, $user_id)
    {
        $data['typestatus_id'] = $typestatus_id;
        $data['public_id'] = $public_id;
        $data['user_id'] = $user_id;
        $res = Db::name('likes')->whereEx($data)
            // ->cache(5)
            ->find();
        if ($res) {
            return $res;
        }
        return false;
    }

    /**
     * 删除收藏
     *
     * @param int $typestatus_id 类型id
     * @param int $public_id 公共id
     * @param int $user_id 用户id
     * @return void
     */
    protected function DelShoucang($typestatus_id, $public_id, $user_id)
    {
        $data['typestatus_id'] = $typestatus_id;
        $data['public_id'] = $public_id;
        $data['user_id'] = $user_id;
        $res = Db::name('likes')->whereEx($data)->find();
        if (!$res) {
            return $this->error('没有该收藏');
        }

        Db::name('likes')->where('id', '=', $res['id'])->delete();
    }


    //*********************************************************************************** */

    /**
     * 添加打电话记录
     *
     * @param int $typestatus_id 类型id
     * @param int $public_id 公共id
     * @param int $uid 用户id
     * @return void
     */
    protected function AddCall($typestatus_id, $public_id, $uid)
    {
        $data['typestatus_id'] = $typestatus_id;
        $data['public_id'] = $public_id;
        $data['uid'] = $uid;
        $data['time'] = time();
        $data['id'] = Db::name('call')->insert($data)->getLastInsertId();
        return $data;
    }



    /**
     * 获取打电话列表
     *
     * @param int $typestatus_id 类型id
     * @param int $public_id 公共id
     * @param int $uid 用户id
     * @return void
     */
    protected function GetCallList($typestatus_id, $public_id = null, $uid = null)
    {
        $data['typestatus_id'] = $typestatus_id;
        if ($public_id)
            $data['public_id'] = $public_id;
        if ($uid)
            $data['uid'] = $uid;
        $list = Db::name('call')->whereEx($data)->order('time desc')->select()->getArray();
        return $list;
    }





    //*********************************************************************************** */

    /**
     * 添加点赞
     *
     * @param int $typestatus_id 类型id
     * @param int $public_id 公共id
     * @param int $uid 用户id
     * @return void
     */
    protected function AddLikes($typestatus_id, $public_id, $uid)
    {
        $data['typestatus_id'] = $typestatus_id;
        $data['public_id'] = $public_id;
        $data['uid'] = $uid;
        $res = Db::name('likes')->whereEx($data)->find();
        if ($res) {
            return $this->error('您已点赞');
        }
        $data['time'] = time();
        $data['id'] = Db::name('likes')->insert($data)->getLastInsertId();
        //加点赞数
        $db = $this->GetTableNameById($typestatus_id);
        if ($db)
            Db::name($db)->where('id', '=', $public_id)->setFieldInc('likes_num')->update();
        return $data;
    }



    /**
     * 是否点赞
     *
     * @param int $typestatus_id 类型id
     * @param int $public_id 公共id
     * @param int $uid 用户id
     * @return void
     */
    protected function IsLikes($typestatus_id, $public_id, $uid)
    {
        $data['typestatus_id'] = $typestatus_id;
        $data['public_id'] = $public_id;
        $data['uid'] = $uid;
        $res = Db::name('likes')->whereEx($data)->find();
        if ($res) {
            return $res;
        }
        return false;
    }

    /**
     * 删除点赞
     *
     * @param int $typestatus_id 类型id
     * @param int $public_id 公共id
     * @param int $uid 用户id
     * @return void
     */
    protected function DelLikes($typestatus_id, $public_id, $uid)
    {
        $data['typestatus_id'] = $typestatus_id;
        $data['public_id'] = $public_id;
        $data['uid'] = $uid;
        $res = Db::name('likes')->whereEx($data)->find();
        if (!$res) {
            return $this->error('没有该点赞');
        }

        //减点赞数
        $db = $this->GetTableNameById($typestatus_id);
        if ($db)
            Db::name($db)->where('id', '=', $public_id)->setFieldDec('likes_num')->update();

        Db::name('likes')->where('id', '=', $res['id'])->delete();
    }





    //*********************************************************************************** */




    /**
     * 获取我是否关注了某用户
     *
     * @param int $ta_id TA的id
     * @param int $me_id 我的id
     * @return void
     */
    protected function GetMyIsfollowUser($ta_id, $me_id)
    {
        $res = Db::name('fans')->where('uid', '=', $ta_id)->where('fans_uid', '=', $me_id)->find();
        if ($res) {
            return true;
        }
        return false;
    }

    /**
     * 获取粉丝关注评论数
     *
     * @param int $uid
     * @return void
     */
    protected function GetUserFansData1($uid)
    {
        $data['fans'] = Db::name('fans')->where('uid', '=', $uid)->count();
        $data['follow'] = Db::name('fans')->where('fans_uid', '=', $uid)->count();
        $data['user'] = Db::name('user')
            ->where('id', '=', $uid)
            // ->fieldRaw('nickname,avatar')
            ->find();
        $data['comment'] = Db::name('comment')->where('uid', '=', $uid)->count();
        $data['likes'] = Db::name('likes')->where('uid', '=', $uid)->count();
        $data['comment_likes'] = $data['likes'] + $data['comment'];

        if ($this->auth->isLogin())
            $data['is_follow'] = $this->GetMyIsfollowUser($uid, $this->auth->user()->id);

        return $data;
    }



    // /**
    //  * 获取对方是否否关注了我
    //  *
    //  * @param int $uid 对方用户id
    //  * @return void
    //  */
    // protected function GetUserIsfollowMy($uid)
    // {
    //     return Db::name('fans')->where('fans_uid',$uid)->where('uid',$this->auth->user()->id)->find();
    // }



    /**
     * 获取评列表
     *
     * @param int $typestatus_id app类型id
     * @param int $public_id 公共id
     * @param int $limit 数量10
     * @param int $page 页1
     * 
     * @return void
     */
    protected function GetCommenList($typestatus_id, $public_id, $limit = 10, $page = 1)
    {
        // return Db::name('comment')->where('typestatus_id', $typestatus_id)->where('public_id', $public_id)->order('time desc')->page($page,$limit)->select()->getArray();
        $list = Db::name('comment')
            ->where('public_id', '=', $public_id)
            ->where('typestatus_id', '=', $typestatus_id)
            ->where(function ($zone) {
                $zone->whereOr('comment_id', '<', 1);
                $zone->whereOr('comment_id', '=', 'null');
            })
            ->order('time desc')
            ->select()->getArray();
        foreach ($list as $key => &$val) {
            $val['comment_num'] = Db::name('comment')
                ->where('public_id', '=', $public_id)
                ->where('typestatus_id', '=', $typestatus_id)
                ->where('comment_id', '=', $val['id'])
                ->count(); //评论数

            // $val['likes'] = Db::name('asklikes')
            //                     ->where('public_id',$public_id)
            //                     ->where('comment_id',$val['id'])
            //                     ->count();//点赞数
            // $val['self_likes'] = $this->GetUserIsAsklikes($public_id,$this->auth->user()->id,$val['id']);

            $val['date'] = $this->TimeStr($val['time']);
            $val['user'] = $this->GetUserData2($val['uid']);
            $val['comment'] = $this->GetComment2Array($public_id, $val['id'], $typestatus_id); // Db::name('comment')->where('ask_id',$ask_id)->where('comment_id',$val['id'])->order('time desc')->select()->getArray();
        }
        return $list;
    }


    /**
     * 获取提问评论数组
     */
    protected function GetComment2Array($public_id, $comment_id = null, $typestatus_id)
    {

        $list = Db::name('comment')
            ->where('public_id', '=', $public_id)
            ->where('typestatus_id', '=', $typestatus_id)
            // ->where('comment_id',$comment_id)
            ->where('top_id', '=', $comment_id)
            ->order('time desc')
            ->select()->getArray();
        foreach ($list as $key => &$val) {
            $val['date'] = $this->TimeStr($val['time']);
            $val['user'] = $this->GetUserData2($val['uid']);

            // $val['self_likes'] = $this->GetUserIsAsklikes($ask_id,$this->auth->user()->id,$val['id']);

            if ($val['comment_uid'] == '' || $val['comment_uid'] == null)
                $val['comment_uid'] = Db::name('comment')->where('id', '=', $val['comment_id'])->value('uid');

            $val['nickname'] = Db::name('user')->where('id', '=', $val['comment_uid'])->value('nickname');
        }
        return $list;
    }


    /**
     * 获取评论数
     *
     * @param int $typestatus_id app类型id
     * @param int $public_id 公共id
     * @return void
     */
    protected function GetCommentNums($typestatus_id, $public_id)
    {
        return Db::name('comment')->where('typestatus_id', '=', $typestatus_id)->where('public_id', '=', $public_id)->count();
    }

    /**
     * 获取点赞数
     *
     * @param int $typestatus_id app类型id
     * @param int $public_id 公共id
     * @return void
     */
    protected function GetLikesNums($typestatus_id, $public_id)
    {
        return Db::name('likes')->where('typestatus_id', '=', $typestatus_id)->where('public_id', '=', $public_id)->count();
    }




    /**
     * 添加浏览记录
     *
     * @param int $viewstatus_id 类型id
     * @param int $public_id 公共id
     * @param int $user_id 用户id
     * @return void
     */
    protected function AddViewlog($viewstatus_id, $public_id, $user_id)
    {
        $data['viewstatus_id'] = $viewstatus_id;
        $data['public_id'] = $public_id;
        $data['user_id'] = $user_id;
        $data['time'] = time();
        $data['id'] = Db::name('viewlog')->insert($data)->getLastInsertId();
        return $data;
    }








    //  _____      __  __         ____ __  __ ____  
    // |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
    //   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
    //   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
    //   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2022/11/05
    //      |_|                                         | TpMeCMS

    /**
     * 删除我的评论
     *
     * @param int $id 评论id
     * @return void
     */
    protected function DelComment($id)
    {
        $comment = Db::name('comment')->where('id', '=', $id)->where('uid', $this->auth->user()->id)->find();
        if (!$comment) {
            return $this->error('该评论不存在');
        }
        // $ask = Db::name('ask')->where('id',$comment['public_id'])->find();
        $ids = [$id];
        //删除下级评论
        $xia_ids = Db::name('comment')->where('top_id', $id)->column('id');
        if ($xia_ids) {
            $ids = array_merge($xia_ids, $ids);
            //在找下级
            $xia2_ids = Db::name('comment')->where('top_id', 'in', $xia_ids)->column('id');
            if ($xia2_ids) {
                $ids = array_merge($xia2_ids, $ids);
            }
            // //删除点赞
            // Db::name('asklikes')->where('comment_id','in',$ids)->delete();

            //删除消息里面的消息
            $user_ids = Db::name('comment')->where('id', 'in', $ids)->column('uid');
            $where_msg['public_id'] = $comment['public_id'];
            $where_msg['user_id'] = ['in', $user_ids];
            $where_msg['status'] = ['in', '3,4'];

            // halt($where_msg);
            Db::name('msg')->where($where_msg)->delete();
        } else {

            if ($comment['comment_id'] > 0) {
                //评论下面评论的
                $asklikes_id = Db::name('asklikes')->where('public_id', $ask['id'])->where('uid', $this->auth->user()->id)->where('comment_id', $comment['comment_id'])->value('id');
                // $this->DelMsg2($comment['uid'],3,$ask['id'],$this->auth->user()->id,$asklikes_id);

            } else {
                $asklikes_id = Db::name('asklikes')->where('public_id', $ask['id'])->where('uid', $this->auth->user()->id)->whereNull('comment_id')->value('id');
                //删除评论点赞
                // $this->DelMsg2($ask['uid'],3,$ask['id'],$this->auth->user()->id,$asklikes_id);

            }
        }




        // $this->DelMsg2($ask['uid'],4,$ask['id'],$this->auth->user()->id,$id);

        $res = Db::name('comment')->where('id', 'in', $ids)->delete();
        return $this->success('删除成功', $res);
    }







    /**
     * 评论提问
     *
     * @param int $typestatus_id 类型id
     * @param int $public_id 提问id
     * @param string $content 内容
     * @param int $comment_id 评论id(可不传)
     * @param string $images 图集(可不传)
     * @return void
     */
    protected function AddComment($typestatus_id, $public_id, $content = null, $comment_id = null, $images = null)
    {
        // $val = Db::name('ask')->where('id',$public_id)->find();
        // if(!$val){
        //    return $this->error('该提问不存在');
        // }
        $where['public_id'] = $public_id;
        $where['typestatus_id'] = $typestatus_id;
        $this->VerifyStr($content);
        if ($comment_id) {

            $res = Db::name('comment')->where('id', '=', $comment_id)->whereEx($where)->find();
            if (!$res) {
                return $this->error('该评论不存在');
            }
            if ($res['comment_id'] > 0) {
                $where['top_id'] = $res['top_id'];
            } else {
                $where['top_id'] = $comment_id;
            }
            $where['comment_uid'] = $res['uid']; //被评论的用户id
        }
        $where['comment_id'] = $comment_id;

        $where['content'] = $content;
        $where['images'] = $images;
        $where['uid'] = $this->auth->user()->id;
        $where['time'] = time();

        $id = Db::name('comment')->insertGetId($where);


        // $this->AddMsg($uid,$status,$public_id,$user_id=null,$title=null);//类型:1=动态点赞,2=动态评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息
        // $this->AddMsg($val['uid'],4,$public_id,$this->auth->user()->id,$this->auth->nickname.'给您的提问回复了');

        if ($comment_id) {
            // if($res['uid']!=$this->auth->user()->id)//自己评论自己不添加
            // $this->AddMsg($res['uid'],4,$public_id,$this->auth->user()->id,$this->auth->nickname.'回复了你的问答评论',$id);
        } else {
            // if($val['uid']!=$this->auth->user()->id)//自己评论自己不添加
            // $this->AddMsg($val['uid'],4,$public_id,$this->auth->user()->id,$this->auth->nickname.'回复了你的问答',$id);
        }

        return $this->success('评论成功', $id);
    }


    //  _____      __  __         ____ __  __ ____  
    // |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
    //   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
    //   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
    //   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2022/11/05
    //      |_|                                         | TpMeCMS



    /**
     * 隐藏手机号
     *
     * @param string $str 手机号
     * @return void
     */
    protected function HideMobile($str = null)
    {
        if (strlen($str)) {
            //    $str = substr_replace($str,'****',3,4);
            $str = substr($str, 0, 3) . '***' . substr($str, -4);
        }
        return $str;
    }

    /**
     * 更新用户密码
     *
     * @param int $user_id 用户id
     * @param string $password 密码
     * @return void
     */
    public function UpdateUserCipher($user_id, $password)
    {
        $cipher['cipher'] = $password;
        $res = Db::name('cipher')->where('user_id', '=', $user_id)->select()->get();
        if ($res) {
            Db::name('cipher')->where('user_id', '=', $res['user_id'])->update($cipher); //自己增加 
        } else {
            $cipher['user_id'] = $user_id;
            Db::name('cipher')->insert($cipher);
        }
    }



    /**
     * 获取用户密码
     *
     * @param int $user_id
     * @return void
     */
    public static function GetUserCipher($user_id)
    {
        return Db::name('cipher')->where('user_id', $user_id)->value('cipher');
    }


    /**
     * 验证店铺支付密码
     *
     * @param int $store_id
     * @param string $pay_password
     * @return void
     */
    protected function VerifyStorePayPassword($store_id, $pay_password)
    {
        if (!$pay_password) {
            return $this->error('请输入支付密码', null, CODE_店铺支付密码错误);
        }
        $store = Db::name('store')->where('id', '=', $store_id)->find();
        if ($store['pay_password'] != md5($pay_password)) {
            return $this->error('支付密码错误', null, CODE_店铺支付密码错误);
        }
        return  'ok';
    }


    /**
     * 验证用户支付密码
     *
     * @param int $user_id
     * @param string $pay_password
     * @return void
     */
    protected function VerifyUserPayPassword($user_id, $pay_password)
    {
        if (!$pay_password) {
            return $this->error('请输入支付密码', null, CODE_用户支付密码错误);
        }
        $store = Db::name('user')->where('id', '=', $user_id)->find();
        if ($store['pay_password'] != md5($pay_password)) {
            return $this->error('支付密码错误', null, CODE_用户支付密码错误);
        }
        return  'ok';
    }

    /**
     * 时间文字
     *
     * @param int $time 时间戳
     * @return void
     */
    protected function TimeToStr($time)
    {
        $xh = 6;
        $now_time = time(); //现在时间

        $today = false; //当天
        $now_date = date('Y-m-d'); //现在日期
        $date = date('Y-m-d', $time);
        if ($now_date == $date)
            $today = true;

        if ($time > ($now_time - 60) && $time < $now_time) {
            $str = '刚刚';
        } elseif ($time > ($now_time - 3600)) {
            $str = strval(intval(($now_time - $time) / 60)) . '分钟前';
        } elseif ($time > ($now_time - 3600 * $xh)) {
            $str = strval(intval(($now_time - $time) / 3600)) . '小时前';
        } elseif ($today) {
            $str = date('H:i', $time);
        } else {
            $str = date('Y-m-d', $time);
        }

        return $str;
    }
}
